使用PHP对多维数组进行排序时如何保留数组索引键值

40
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" }
}

我正在使用上面的数组,这个多维数组被称为$stats

我想按数量对这个数组进行排序。

所以多维数组的第一个数组是1016,然后是1018、1017等等。

我已经通过以下方式实现了这一点:

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

这个方案运行得很好!

但问题在于,当头部数组(ID 为 1019、1018、1017 等)被排序时,它的索引消失了。我想保留数组的索引。

我该怎么做?

1个回答

105

我认为你需要的是uasort

来自PHP官方文档

使用用户自定义比较函数对数组进行排序并保持索引关联性

示例

  uasort($stats, 'compare');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接