Keeping array index key when sorting a multidimensional array with PHP

不羁岁月 提交于 2019-12-18 18:49:50

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/13425117/keeping-array-index-key-when-sorting-a-multidimensional-array-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!