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?
array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions. Associative (string) keys will be maintained, but numeric keys will be re-indexed. Note: If two members compare as equal, they retain their original order.
Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements.
The arsort() function sorts an associative array in descending order, according to the value. Tip: Use the asort() function to sort an associative array in ascending order, according to the value. Tip: Use the krsort() function to sort an associative array in descending order, according to the key.
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'); 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With