PHP排序多维数组的最佳方法?

时间:2013-01-15 04:21:06

标签: php arrays sorting methods multidimensional-array

  

可能重复:
  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");

然后我想按照 $fruits[] 对此price数组进行排序。
所以它应该

$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()等。)?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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
        )

)
相关问题