使用PHP对多维数组进行排序时保持数组索引键 [英] Keeping array index key when sorting a multidimensional array with PHP

查看:204
本文介绍了使用PHP对多维数组进行排序时保持数组索引键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

I am working with the array above. This multi dimensional array is called $stats.

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

I would like to sort this array, by the quantity.

因此,多维多维数组具有其第一个数组1016,然后是1018、1017,依此类推.

So that the multidim array is has its first array 1016 then 1018, 1017 and so on.

我这样做的方法是:

                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等)在排序时消失了.我想保留数组索引.

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.

我该怎么做?

推荐答案

我认为您需要的是uasort

I think what you need is uasort

从PHP DOC读取

使用用户定义的比较功能并维护索引关联

示例

  uasort($stats, 'compare');

这篇关于使用PHP对多维数组进行排序时保持数组索引键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆