Search code examples
phparrayssortingmultidimensional-arrayksort

Sort only the keys in each row of a 2d array


I have an array in the following format. How can I sort each row's data by its keys in an ascending fashion?

[
    [
        40 => 2,
        80 => 1,
        20 => 0,
        60 => 0,
        100 => 0,
    ],
    [
        60 => 2,
        80 => 1,
        20 => 0,
        40 => 0,
        100 => 0,
    ],
]

Expected result:

[
    [
        20 => 0,
        40 => 2,
        60 => 0,
        80 => 1,
        100 => 0,
    ],
    [
        20 => 0,
        40 => 0,
        60 => 2,
        80 => 1,
        100 => 0,
    ],
]

I tried using array_values() and array_combine(), but with no luck.


Solution

  • Use array_combine (http://php.net/manual/en/function.array-combine.php) to combine the arrays and then use ksort (http://php.net/manual/en/function.ksort.php) to sort the keys.