How to sort an array of associative arrays by value of a given key in PHP?

I have a multidimensional array in php, and I want to naturally sort the array based on key value. The array in question:

Array
(
    [0] => Array
        (
            [width] => medium
            [measurement] => 50-21-145
        )

    [1] => Array
        (
            [width] => s-m
            [measurement] => 47-21-140
        )

    [2] => Array
        (
            [width] => small
            [measurement] => 50-21-135
        )

    [3] => Array
        (
            [width] => m-l
            [measurement] => 52-21-145
        )

)



I have attempted a few things so far, but I am having no luck. Using uksort it doesn't work, and I don't want to have to go as far as writing a custom comparator for natural sorting order if I don't have to. I also attempted sorting the keys individually, however that seemed to not work.

I want the above array as: 
Array
(
    [0] => Array
        (
            [width] => small
            [measurement] => 50-21-135
        )

    [1] => Array
        (
            [width] => s-m
            [measurement] => 47-21-140
        )

    [2] => Array
        (
            [width] => medium
            [measurement] => 50-21-145
        )

    [3] => Array
        (
            [width] => m-l
            [measurement] => 52-21-145
        )

)


Asked 25 Oct, 17 at 05:24 AM

Tim Martin
Php Array

Answer

Hi Tim, 


Use the following sorting method:

usort($widthArr, function ($item1, $item2) {
if ($item1['width'] == $item2['width']) return 0;
return $item1['width'] > $item2['width'] ? -1 : 1;
});

It will work :)

like

There is a little modification in the code, you can use this updated code with better sorting:


usort($widthArr, function ($item1, $item2) {

$order = [ 'small' => 0, 'medium' => 1, 'large' => 2, 's-m' => 3, 'm-l' => 4, 'xl' => 5 ];
if ($item1['width'] == $item2['width']) return 0;
return $order[$item1['width']] < $order[$item2['width']] ? -1 : 1;
});

like