Search code examples
phparrayssortingmultidimensional-array

Sort the first level of a multidimensional array by its dynamic second-level key


I have to sort multidimensional array by key and I need some recomendation how to do it.

I tried using ksort() and other php built-in functions, but none of them helped me.

This is my array, which I want to sort by key:

Array
(
[0] => Array
    (
        [20190529] => Array
            (
                [30] => Array
                    (
                        [17] => Array
                            (
                                [3846] => 0
                            )

                    )

            )

    )

[1] => Array
    (
        [20190516] => Array
            (
                [31] => Array
                    (
                        [17] => Array
                            (
                                [512] => 0
                            )

                    )

            )

    )

)

In that case, keys are 20190529 and 20190516


Solution

  • Working demo.

    You can use array_multisort to achieve your requirement.

    $keys = [];
    foreach($arr as $k => $item){
        $keys[] = key($item);
    }
    array_multisort($keys, SORT_NATURAL, $arr);
    

    array_multisort — Sort multiple or multi-dimensional arrays

    SORT_NATURAL - compare items as strings using "natural ordering" like natsort().