简体   繁体   中英

PHP - How to sort multidimensional array by 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

I modified my array like that:

Array
(
[0] => Array
    (
        [DATE] => 20190503
        [DEAL] => 30
        [IBLOCK] => 18
        [AMOUNT] => 2500
        [PAYED] => 0
    )

[1] => Array
    (
        [DATE] => 20190516
        [DEAL] => 31
        [IBLOCK] => 17
        [AMOUNT] => 512
        [PAYED] => 0
    )
)

then I used usort() :

function cmp($a, $b) {
    return $a['DATE'] - $b['DATE'];
}

usort($mydata, "cmp");

And it did job for me :) but Now I have to modify my array again to return first look.

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM