lacyeex lacyeex - 3 months ago 7
PHP Question

Sort multidimensional array in PHP using foreach

For example i have an array named

$slice
like this :

Array
(
[0] => Array
(
[0] => 12
[1] => 4
[2] => 2
[3] => 8
[4] => 20
)

[1] => Array
(
[0] => 9
[1] => 7
[2] => 1
[3] => 10
[4] => 23
)

)


I want to sort array above so the output will be like this :

Array
(
[0] => Array
(
[0] => 2
[1] => 4
[2] => 8
[3] => 12
[4] => 20
)

[1] => Array
(
[0] => 1
[1] => 7
[2] => 9
[3] => 10
[4] => 23
)

)


Then i tried to use foreach and array_multisort, and when i use print_r the result is 1 for each col :

foreach ($slice1 as $col) {
$slicesort[] = array_multisort($col);
}

output :
Array
(
[0] => 1
[1] => 1
)

Answer

array_multisort sorts the array in place, it does not return the sorted array. You need to use it like this:

foreach ($slice1 as $col) {
    array_multisort($col);
    $slicesort[] = $col;
}

Having said this, array_multisort is somewhat overkill here, and I'm not sure that you really need to create a copy of the array. This will do just fine:

foreach ($slice1 as &$col) {
    sort($col);
}

This applies sort to each array within $slice1 by reference, and thereby orders $slice1 in place.