Keeping array index key when sorting a multidimensional array with PHP

Karem picture Karem · Nov 16, 2012 · Viewed 25.6k times · Source
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?

Answer

Baba picture Baba · Nov 16, 2012

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');