通过其值阵列中的向上/向下移动一个项目 [英] Moving up/down an item in the array by its value
问题描述
我找不到对重整/由位移由它的价值交换的数组项的有效解决方案 - 1
或 + 1
。我的表上发出命令,如果用户想要通过向上或向下移动的值来顺序移位,阵列应换成所需的项目的值向上或向下,例如:
I cannot find an effective solution on rearranging/swapping an array item by its value by shifting by - 1
or + 1
. I'm making an order on tables, if the user wants to shift the order by moving the value upwards or downwards, the array should swap the value of the desired item upwards or downwards, for example:
如果用户想要向上移动的项目顺序为:
$desired_item_to_move = 'banana';
$default_order = array('orange', 'apple', 'banana', 'pineapple', 'strawberry');
// Typically it should return this:
array('orange', 'banana', 'apple', 'pineapple', 'strawberry');
正如你可以看到香蕉
和苹果
已被交换,由于香蕉
向上移动,如果用户想往下移动,应该换菠萝
到香蕉
(来自第一阵列)等
As you can see that banana
and apple
has been swapped, due to banana
is moved upwards, if the user wants to move it down, it should swap pineapple
to banana
(from the first array) and so on.
我看了看周围的功能, array_replace
最接近,但只替换数组。
I looked around on functions, array_replace
was closest, but it only replaces arrays.
推荐答案
移了(假设你已经检查的项目是不是已经是第一个):
Shifting up (assuming you've checked that the item is not already the first one):
$item = $array[ $index ];
$array[ $index ] = $array[ $index - 1 ];
$array[ $index - 1 ] = $item;
下移:
$item = $array[ $index ];
$array[ $index ] = $array[ $index + 1 ];
$array[ $index + 1 ] = $item;
这篇关于通过其值阵列中的向上/向下移动一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!