0

可能重复:
如何在 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纯粹的方法来实现这件事吗?
  • [或者] 我们不能仅仅通过使用/picking 来自一些 PHP 纯内置数组排序方法(例如:sort()、usort()、asort()、array_multisort来纠正这个多维数组排序问题吗? (), ETC..) ?
4

2 回答 2

2
usort ($fruits, function($a, $b) { return $a['price'] > $b['price'] ? 1 : ($a['price'] == $b['price'] ? 0 : -1); });
于 2013-01-15T04:28:27.813 回答
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
        )

)
于 2013-01-15T04:29:39.583 回答