假设我有以下多维数组:
$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
是否有任何纯粹的方法来实现这个目标?答案 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
)
)