我找不到一个有效的解决方案,可以通过移动- 1
或+ 1
来重新排列/交换数组项的值。我正在对表格进行订单,如果用户想要通过向上或向下移动值来移动订单,则数组应该向上或向下交换所需项目的值,例如:
如果用户想要向上移动商品订单:
$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
和apple
已被交换,由于banana
向上移动,如果用户想要将其向下移动,则应该交换pineapple
} banana
(来自第一个数组),依此类推。
我查看了函数,array_replace
最接近,但它只替换了数组。
答案 0 :(得分:15)
向上移动(假设你已经检查过该项目不是第一个):
$item = $array[ $index ];
$array[ $index ] = $array[ $index - 1 ];
$array[ $index - 1 ] = $item;
向下移动:
$item = $array[ $index ];
$array[ $index ] = $array[ $index + 1 ];
$array[ $index + 1 ] = $item;
答案 1 :(得分:7)
有关将数组元素从一个位置移动到另一个位置的更一般问题的有用函数:
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);
注意,无需检查您是否已经在阵列的开头/结尾。另请注意,此函数不保留数组键 - 保留键时移动元素更加繁琐。
答案 2 :(得分: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
。