交换多维数组中的元素及其上方的兄弟元素。
我希望数组中具有选定索引的元素与他上方的元素交换它的位置。
- 从它的位置(N)到位置(N-1)的元素
- 我希望位置(N-1)处的元素进入位置(N),
- 结果索引应该正确地反映它们在数组中的新顺序。
array_values($tmparr);
确实对索引进行了正确排序 - 要交换的目标元素可以转到 Position(0),但永远不会从 Position(0) 开始
- 如果在位置(0)处要向下交换的元素应该在位置(1)处而不是在数组的末尾。
虽然这个函数在语义上解释了我想要做什么,但它根本不起作用。
function swaparray($tmparr,$posa,$posb){
$vala = $tmparr[$posa];
$valb = $tmparr[$posb];
$tmparr[$posa] = $valb;
$tmparr[$posb] = $vala;
return $tmparr; }
第二个函数将预期的目标向上移动,但如果他在位置 0,上面的元素被向上推并到列表的末尾,它不会在目标下方,所以它不能按预期工作
function swaparray($tmparr,$posa,$posb){
$vala = $tmparr[$posa];
$valb = $tmparr[$posb];
unset($tmparr[$posa]);
unset($tmparr[$posb]);
$tmparr[$posa] = $valb;
$tmparr[$posb] = $vala;
$tmparr = array_values($tmparr);
return $tmparr;
}
进一步阅读我的问题是接缝 Array_splice() 可以解决问题。您对此有何意见?
编辑答案:(PHP >= 4.3.8)
Array_splice() 的工作解决方案
function swaparray($array, $n) {
// taking out at $n
$out = array_splice($array, $n, 1);
// adding in at $n - 1
array_splice($array, $n - 1, 0, $out);
return $array;
}
这是原始的多维数组
Array ( [0] => Array ( [key1] => 1 [key2] => 1 [key3] => 1 [key4] => 1 )
[1] => Array ( [key1] => 2 [key2] => 2 [key3] => 2 [key4] => 2 )
[2] => Array ( [key1] => 3 [key2] => 3 [key3] => 3 [key4] => 3 )
[3] => Array ( [key1] => 4 [key2] => 4 [key3] => 4 [key4] => 4 ) )
这是我想要它做的一个摘录/示例。
[0] key1=1 key2=1 key3=1 key4=1
[1] key1=2 key2=2 key3=2 key4=2
[2] key1=3 key2=3 key3=3 key4=3 <-
[3] key1=4 key2=4 key3=4 key4=4
交换数组($tmparr,2);
[0] key1=1 key2=1 key3=1 key4=1
[1] key1=3 key2=3 key3=3 key4=3 <-
[2] key1=2 key2=2 key3=2 key4=2
[3] key1=4 key2=4 key3=4 key4=4
交换数组($tmparr,1);
[0] key1=3 key2=3 key3=3 key4=3 <-
[1] key1=1 key2=1 key3=1 key4=1
[2] key1=2 key2=2 key3=2 key4=2
[3] key1=4 key2=4 key3=4 key4=4
交换数组($tmparr,1);
[0] key1=1 key2=1 key3=1 key4=1 <-
[1] key1=3 key2=3 key3=3 key4=3
[2] key1=2 key2=2 key3=2 key4=2
[3] key1=4 key2=4 key3=4 key4=4