如何按嵌套在其中的元素对 PHP 数组进行排序? [英] How do I sort a PHP array by an element nested inside?

查看:29
本文介绍了如何按嵌套在其中的元素对 PHP 数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的数组:

<前>大批([0] => 数组('姓名' => 星期五"'重量' => 6)[1] => 数组('名称' => 星期一"'重量' => 2))

我想获取该数组中的最后一个值(权重"),并使用它对主要数组元素进行排序.所以,在这个数组中,我想对它进行排序,使 'Monday' 元素出现在 'Friday' 元素之前.

解决方案

您可以使用 <代码>usort 为:

function cmp($a, $b) {返回 $a['weight'] - $b['weight'];}usort($arr,"cmp");

I have an array like the following:

Array
(
    [0] => Array
        (
            'name' => "Friday"
            'weight' => 6
        )
    [1] => Array
        (
            'name' => "Monday"
            'weight' => 2
        )
)

I would like to grab the last values in that array (the 'weight'), and use that to sort the main array elements. So, in this array, I'd want to sort it so the 'Monday' element appears before the 'Friday' element.

解决方案

You can use usort as:

function cmp($a, $b) {
   return $a['weight'] - $b['weight'];
}

usort($arr,"cmp");

这篇关于如何按嵌套在其中的元素对 PHP 数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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