Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping array index key when sorting a multidimensional array with PHP

Tags:

php

usort

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?

like image 371
Karem Avatar asked Nov 16 '12 22:11

Karem


People also ask

How do you sort a multi-dimensional array by key?

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.

How do I sort a multi-dimensional array in PHP?

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.

How do you sort an array of associative arrays by the value of a given key in PHP?

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.


1 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'); 
like image 66
Baba Avatar answered Sep 23 '22 00:09

Baba