如何按PHP中给定键的值对关联数组的数组进行排序? [英] How to sort an array of associative arrays by value of a given key in PHP?
本文介绍了如何按PHP中给定键的值对关联数组的数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定这个数组:
$inventory = array(
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
我想按价格对 $inventory
的元素进行排序以获得:
I would like to sort $inventory
's elements by price to get:
$inventory = array(
array("type"=>"pork", "price"=>5.43),
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
);
我该怎么做?
推荐答案
你说得对,你要找的函数是 array_multisort()
.
You are right, the function you're looking for is array_multisort()
.
这是直接取自手册并适合您的情况的示例:
Here's an example taken straight from the manual and adapted to your case:
$price = array();
foreach ($inventory as $key => $row)
{
$price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);
从 PHP 5.5.0 开始,您可以使用 array_column()
而不是 foreach:
As of PHP 5.5.0 you can use array_column()
instead of that foreach:
$price = array_column($inventory, 'price');
array_multisort($price, SORT_DESC, $inventory);
这篇关于如何按PHP中给定键的值对关联数组的数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文