php数组获得关联数组最大,如何通过PHP中的给定键的值来对关联数组的数组进行排序?...

文章目录

给定这个数组:$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),

);

我该怎么做?

下面是直接从手册中取得的一个例子,并根据您的情况进行调整:$price = array();

foreach ($inventory as $key => $row)

{

$price[$key] = $row['price'];

}

array_multisort($price, SORT_DESC, $inventory);

PHP 7+

从PHP 7开始,可以使用usort,并使用匿名函数使用太空飞船运营商来比较元素。

您可以像这样按升序排序:usort($inventory, function ($item1, $item2) {

return $item1['price'] <=> $item2['price'];

});

或者像这样降序排序:usort($inventory, function ($item1, $item2) {

return $item2['price'] <=> $item1['price'];

});

为了理解这是如何工作的,请注意,usort需要一个用户提供的比较函数,它的行为必须如下(来自文档):The comparison function must return an integer less than, equal to, or

greater than zero if the first argument is considered to be respectively less

than, equal to, or greater than the second.

还要注意&lt; =&gt;,宇宙飞船运营商,returns 0 if both operands are equal, 1 if the left is greater, and -1 if

the right is greatermakes writing ordering callbacks for use with usort() easier

PHP 5.3+

PHP 5.3引入了匿名函数,但是还没有太空船运营商。我们仍然可以使用usort对我们的数组进行排序,但是它有点冗长和难以理解:usort($inventory, function ($item1, $item2) {

if ($item1['price'] == $item2['price']) return 0;

return $item1['price'] < $item2['price'] ? -1 : 1;

});

注意,尽管处理整数值的比较器只是返回值的差异,比如$ item2 ['price'] - $ item1 ['price']‘,我们

float, will result in an internal cast to integer of the callback’s return

value. So values such as 0.99 and 0.1 will both be cast to an integer value of

0, which will compare such values as equal.

在PHP 5.x中使用usort时,这是一个重要的陷阱。

这个答案的原始版本犯了这个错误,但我累积成千上万的意见显然没有任何人注意到严重的错误tenvotes

。像我这样的缺乏智能可以使比较函数变得简单的原因正是PHP 7中易于使用的飞船运算符被添加到语言中的原因。

未经作者同意,本文严禁转载,违者必究!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值