【发布时间】:2013-01-15 04:21:06
【问题描述】:
假设我有以下多维数组:
$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