<?php
$str = ['a','b','c','d'];
// 交换索引
function swapArray($arr, $index1, $index2) {
$arr[$index1] = array_splice($arr,$index2,1,$arr[$index1])[0];
return $arr;
}
// 上移 将当前数组index索引与后面一个元素互换位置,向数组后面移动一位
function moveUp($arr, $index) {
return swapArray($arr, $index, $index - 1);
}
// 下移 将当前数组index索引与前面一个元素互换位置,向数组前面移动一位
function moveDown($arr, $index) {
return swapArray($arr, $index, $index + 1);
}
var_dump(moveUp($str,2));
var_dump(moveDown($str,2));
?>
// 上移结果
Array
(
[0] => a
[1] => c
[2] => b
[3] => d
)
// 下移结果
Array
(
[0] => a
[1] => b
[2] => d
[3] => c
)