【问题标题】:Keeping array index key when sorting a multidimensional array with PHP使用 PHP 对多维数组进行排序时保留数组索引键
【发布时间】:2012-11-05 16:21:45
【问题描述】:
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

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

因此 multidim 数组的第一个数组是 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 等)在排序时会消失。我想保留数组索引。

我该怎么做?

【问题讨论】:

    标签: php usort


    【解决方案1】:

    我想你需要的是uasort——

    FROM PHP DOC

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

    例子

      uasort($stats, 'compare');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-27
      • 2015-11-02
      • 1970-01-01
      • 2013-12-30
      • 1970-01-01
      • 2017-07-12
      相关资源
      最近更新 更多