Home > Mobile >  Sort multi-dimentional inner array PHP
Sort multi-dimentional inner array PHP

Time:04-14

I have been trying to sort multi-dimensional inner array, i have tried usort() and array_multisort() method but doesn't worked in my case.

$array = [
        [
            'sizes'=>[
                [
                    'weight'=>25,
                    'height'=>110
                ], [
                    'weight'=>45,
                    'height'=>110
                ],

            ]
        ],
        [
            'sizes'=>[
                [
                    'weight'=>80,
                    'height'=>120
                ],[
                    'weight'=>20,
                    'height'=>120
                ]
                ]

        ]
    ];

I need to sort the above array based on weight in such a way that if sort by highest weight array should return sizes block with highest weight and vice-versa. In this case "weight": 80 is the highest and if sort by lowest 1st "weight": 20 should come 1st.

Expected output after sort for both SORT_ASC and SORT_DESC

 $array = [
        [
            'sizes'=>[
                [
                    'weight'=>80,
                    'height'=>120
                ],[
                    'weight'=>20,
                    'height'=>120
                ]
                ]

        ],
        [
            'sizes'=>[
                [
                    'weight'=>25,
                    'height'=>110
                ], [
                    'weight'=>45,
                    'height'=>110
                ],

                ]
            ]
    ];

CodePudding user response:

You can use array_column to extract the weight values from a sub-array, then use max on those, and then the <=> comparison operator to compare those two maxima:

usort($array, function($a, $b) {
    return max(array_column($b['sizes'], 'weight')) <=>
           max(array_column($a['sizes'], 'weight'));
});

This would be for descending order, for ascending you would need to switch $a and $b around, resp. multiply with -1.

  • Related