【问题标题】:PHP Best way to Sort Multi-dimentional Array? [duplicate]PHP 对多维数组进行排序的最佳方法? [复制]
【发布时间】:2013-01-15 04:21:06
【问题描述】:

可能重复:
How do I sort a multidimensional array in php

假设我有以下多维数组:

$fruits[] = array("name"=>"orange", "price"=>3, "code"=>"A45");
$fruits[] = array("name"=>"apple", "price"=>2, "code"=>"W71");
$fruits[] = array("name"=>"grape", "price"=>4, "code"=>"G11");

然后我想通过它的 price 对这个 $fruits[] 数组进行排序。
所以它应该是:

$fruits[] = array("name"=>"apple", "price"=>2, "code"=>"W71");
$fruits[] = array("name"=>"orange", "price"=>3, "code"=>"A45");
$fruits[] = array("name"=>"grape", "price"=>4, "code"=>"G11");

然后我在网上浏览了很多,最后我发现了来自php manual 的以下一个(我用上面的数组调整了变量名):

// Obtain a list of columns
foreach ($fruits as $key => $value) {
    $name[$key]  = $value['name'];
    $price[$key] = $value['price'];
    $code[$key] = $value['code'];
}

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($price, SORT_ASC, $fruits);

好的,知道了!然后$fruits[] 数组按price 值正确排序。
好吧,这是我的一些担忧:

  • 据我之前了解,我们不应该添加/使用任何附加/自定义代码来使用排序机制。 (相反,我认为我们应该使用纯内置方法。)
  • 在这里我怀疑性能,因为它内部有预先自定义的foreach 循环,当我们拥有真正的巨大阵列时,这可能会大大降低速度。 (就像我现在一样)

所以现在我想问的是:

  • PHP 有什么纯方法可以实现这个东西吗?
  • [或]我们不能通过仅使用/从一些 PHP 纯内置数组排序方法(例如:sort() , usort(), asort(), array_multisort(), 等等..) ?

【问题讨论】:

    标签: php arrays sorting methods multidimensional-array


    【解决方案1】:
    usort ($fruits, function($a, $b) { return $a['price'] > $b['price'] ? 1 : ($a['price'] == $b['price'] ? 0 : -1); });
    

    【讨论】:

      【解决方案2】:

      usort 听起来像你要找的东西:

      <?
      $fruits[] = array("name"=>"orange", "price"=>3, "code"=>"A45");
      $fruits[] = array("name"=>"apple", "price"=>2, "code"=>"W71");
      $fruits[] = array("name"=>"grape", "price"=>4, "code"=>"G11");
      usort($fruits, function($a, $b){return $a['price'] - $b['price'];});
      print_r($fruits);
      ?>
      

      产生:

      Array
      (
          [0] => Array
              (
                  [name] => apple
                  [price] => 2
                  [code] => W71
              )
      
          [1] => Array
              (
                  [name] => orange
                  [price] => 3
                  [code] => A45
              )
      
          [2] => Array
              (
                  [name] => grape
                  [price] => 4
                  [code] => G11
              )
      
      )
      

      【讨论】:

        猜你喜欢
        • 2014-09-16
        • 1970-01-01
        • 2013-07-20
        • 1970-01-01
        • 2010-12-20
        • 1970-01-01
        • 2010-09-07
        • 1970-01-01
        相关资源
        最近更新 更多