Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort multi-dimentional inner array PHP

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

                ]
            ]
    ];

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading