Home » Php » usort – Keeping array index key when sorting a multidimensional array with PHP

usort – Keeping array index key when sorting a multidimensional array with PHP

Posted by: admin April 23, 2020 Leave a comment

Questions:
array(10) { 
[1019]=> array(3) { ["quantity"]=> int(0) ["revenue"]=> int(0) ["seller"]=> string(5) "Lenny" } 
[1018]=> array(3) { ["quantity"]=> int(5) ["revenue"]=> int(121) ["seller"]=> string(5) "Lenny" } 
[1017]=> array(3) { ["quantity"]=> int(2) ["revenue"]=> int(400) ["seller"]=> string(6) "Anette" } 
[1016]=> array(3) { ["quantity"]=> int(25) ["revenue"]=> int(200) ["seller"]=> string(6) "Samuel" } 
[1015]=> array(3) { ["quantity"]=> int(1) ["revenue"]=> int(300) ["seller"]=> string(6) "Samuel" } 
[1014]=> array(3) { ["quantity"]=> string(2) "41" ["revenue"]=> string(5) "18409" ["seller"]=> string(6) "Samuel" }
}

I am working with the array above. This multi dimensional array is called $stats.

I would like to sort this array, by the quantity.

So that the multidim array is has its first array 1016 then 1018, 1017 and so on.

I have done this by:

                function compare($x, $y) {
                    if ( $x['quantity'] == $y['quantity'] )
                    return 0;
                    else if ( $x['quantity'] > $y['quantity'] )
                    return -1;
                    else
                    return 1;
                }
                usort($stats, 'compare');

Which works just fine!

But the issue is that the head array index (the ID’s, 1019, 1018, 1017 etc) disappears when its getting sorted. I would like to keep the array indexes.

How can I do this?

How to&Answers:

I think what you need is uasort

FROM PHP DOC

Sort an array with a user-defined comparison function and maintain index association

Example

  uasort($stats, 'compare');