我找不到一个有效的解决方案,通过移动- 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');
Run Code Online (Sandbox Code Playgroud)
正如你可以看到,banana并apple已换,由于banana向上移动,如果用户想往下移动,就应该换pineapple到banana(从第一阵列)等.
我查看函数,array_replace最接近,但它只替换数组.
JJJ*_*JJJ 15
向上移动(假设您已检查该项目不是第一个):
$item = $array[ $index ];
$array[ $index ] = $array[ $index - 1 ];
$array[ $index - 1 ] = $item;
Run Code Online (Sandbox Code Playgroud)
向下移动:
$item = $array[ $index ];
$array[ $index ] = $array[ $index + 1 ];
$array[ $index + 1 ] = $item;
Run Code Online (Sandbox Code Playgroud)
对于将数组元素从一个位置移动到另一个位置的更一般问题的有用函数:
function array_move(&$a, $oldpos, $newpos) {
if ($oldpos==$newpos) {return;}
array_splice($a,max($newpos,0),0,array_splice($a,max($oldpos,0),1));
}
Run Code Online (Sandbox Code Playgroud)
然后,这可用于解决原始问题中的特定问题:
// shift up
array_move($array,$index,$index+1);
// shift down
array_move($array,$index,$index-1);
Run Code Online (Sandbox Code Playgroud)
注意,不需要检查您是否已经在阵列的开头/结尾.另请注意,此函数不保留数组键 - 保留键时移动元素更加繁琐.
| 归档时间: |
|
| 查看次数: |
13837 次 |
| 最近记录: |