如何在PHP中按给定键的值对关联数组进行排序? [英] How to sort an array of associative arrays by value of a given key in PHP?

查看:83
本文介绍了如何在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),

);

我该怎么做?

推荐答案

是的,您要查找的功能是

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆