Search code examples
phparrayssortingmultidimensional-array

Sort subarray values of a 2d array and preserve first level keys


I find other thread about sort multidimensional array, but it's not the same problem.

$arr[22][] = 45;
$arr[22][] = 44;
$arr[22][] = 99;

$arr[23][] = 95;
$arr[23][] = 55;
$arr[23][] = 1;

echo "<pre>";
print_r($arr);
echo "</pre>";

I want to sort the value inside subarray, not the value between sub array.

The expected result is

[22] => Array [0 ] => 44 [1] => 45 [2] => 99

[23] => Array [0 ] => 1 [1] => 55 [2] => 95

I try with

array_multisort($arr[22], SORT_ASC, SORT_NUMERIC
                , $arr[23], SORT_ASC, SORT_NUMERIC);

but it's not correct anyway.

How could I do?


Solution

  • Simple enough:

    foreach($arr as &$v) {
        sort($v);
    }
    

    The &$v allow the values to be iterated over by reference, allowing modification inside the foreach loop (and thus sorting of each subarray).