使用PHP排序多维数组时保持数组索引键

时间:2021-02-20 21:35:02
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?

我该怎么做呢?

1 个解决方案

#1


77  

I think what you need is uasort

我想你需要的是uasort -

FROM PHP DOC

从PHP文档

Sort an array with a user-defined comparison function and maintain index association

使用用户定义的比较函数对数组进行排序并维护索引关联

Example

例子

  uasort($stats, 'compare');

#1


77  

I think what you need is uasort

我想你需要的是uasort -

FROM PHP DOC

从PHP文档

Sort an array with a user-defined comparison function and maintain index association

使用用户定义的比较函数对数组进行排序并维护索引关联

Example

例子

  uasort($stats, 'compare');