php 使用PHP对多维数组进行排序时保留数组索引键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13425117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Keeping array index key when sorting a multidimensional array with PHP
提问by Karem
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.
我正在使用上面的数组。这个多维数组称为$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.
因此,multidim 数组的第一个数组是 1016,然后是 1018、1017,依此类推。
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.
但问题是头部数组索引(ID、1019、1018、1017 等)在排序时消失了。我想保留数组索引。
How can I do this?
我怎样才能做到这一点?
回答by Baba
I think what you need is uasort—
我认为你需要的是uasort——
Sort an array with a user-defined comparison function and maintain index association
使用用户定义的比较函数对数组进行排序并保持索引关联
Example
例子
uasort($stats, 'compare');

