Swap-up element in a multidimensional array with the sibling above it.
I want the element with the selected index in the array to swap it's position with the one above him.
- The element from it's position(N) to go to position(N-1)
- I want the element at position(N-1) to go at position(N),
- The resulting index should be reflecting correctly their new order in the array.
array_values($tmparr);
does sort the index correctly - The Target Element to swap up can go to Position(0) but will never start at Position(0)
- The Element to swap down if at Position(0) Should go at position(1) not go at the End of the array.
Although this function explain semantically what i want to do it does not work at all.
function swaparray($tmparr,$posa,$posb){
$vala = $tmparr[$posa];
$valb = $tmparr[$posb];
$tmparr[$posa] = $valb;
$tmparr[$posb] = $vala;
return $tmparr; }
The 2nd function shifts the intended target up but the above element is pushed up and goes to the end of the list if he is at position 0, it does not go under the target, so it doesnt work as intended it
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;
}
Reading further about my issue is seams Array_splice() could do the trick. What are your inputs about this?
Edit Answer: (PHP >= 4.3.8 )
The working solution with 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;
}
Here is the original multidimensional 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 ) )
Here is an excerpt / exemple of want i wanted it to do.
[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
swaparray($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
swaparray($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
swaparray($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