通过其值将数组中的项目上移/下移

5

我无法找到一种有效的方法来通过向上或向下移动值来重新排列/交换数组项。我正在对表格进行排序,如果用户想通过向上或向下移动值来改变顺序,则数组应该向上或向下交换所需项目的值,例如:

如果用户想将项目顺序向上移动:

$desired_item_to_move = 'banana';

$default_order = array('orange', 'apple', 'banana', 'pineapple', 'strawberry');

// Typically it should return this:

array('orange', 'banana', 'apple', 'pineapple', 'strawberry');

正如您所看到的,由于将banana向上移动,因此bananaapple已经交换位置,如果用户想将其向下移动,则应将pineapple(来自第一个数组)与banana进行交换,以此类推。

我在函数中查找,array_replace最接近,但它仅替换数组。

3个回答

16

向上移动(假设您已检查该项不是第一个):

$item = $array[ $index ];
$array[ $index ] = $array[ $index - 1 ];
$array[ $index - 1 ] = $item;

向下移动:

$item = $array[ $index ];
$array[ $index ] = $array[ $index + 1 ];
$array[ $index + 1 ] = $item;

8

针对将数组中的元素从一个位置移动到另一个位置的更一般问题,以下是有用的函数:

function array_move(&$a, $oldpos, $newpos) {
    if ($oldpos==$newpos) {return;}
    array_splice($a,max($newpos,0),0,array_splice($a,max($oldpos,0),1));
}

这样就可以用来解决原问题中的具体问题:
// shift up
array_move($array,$index,$index+1);
// shift down
array_move($array,$index,$index-1);

请注意,无需检查您是否已经在数组的开头/结尾。请注意,此函数不保留数组键 - 在保留键的同时移动元素更加麻烦。

0
$ret = array();
for ($i = 0; $i < count($array); $i++) {
    if ($array[$i] == $desired_item_to_move && $i > 0) {
        $tmp = array_pop($ret);
        $ret[] = $array[$i];
        $ret[] = $tmp;
    } else {
        $ret[] = $array[$i];
    }
}

这将移动所有所需元素的实例,将新数组放入$ret中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接