"fruit", "price"=>3.50), array("type"=>"milk", "pric-6ren">
gpt4 book ai didi

php - 如何按PHP中给定键的值对关联数组的数组进行排序?

转载 作者:IT老高 更新时间:2023-10-28 11:36:43 26 4
gpt4 key购买 nike

给定这个数组:

$inventory = array(

array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),

);

我想按价格对$inventory的元素进行排序得到:

$inventory = array(

array("type"=>"pork", "price"=>5.43),
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),

);

我该怎么做?

最佳答案

你是对的,你要找的函数是array_multisort() .

以下是直接取自手册并根据您的情况改编的示例:

$price = array();
foreach ($inventory as $key => $row)
{
$price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);

从 PHP 5.5.0 开始,您可以使用 array_column() 代替 foreach:

$price = array_column($inventory, 'price');

array_multisort($price, SORT_DESC, $inventory);

关于php - 如何按PHP中给定键的值对关联数组的数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1597736/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com