php - 多维数组第四层中的第三层数据按列降序排序

标签 php arrays sorting multidimensional-array

我有一个复杂的多维数组;结构是这样的:

[
    [
        'countries' => [
            ['country_code' => 'US', 'growth' => 3.57],
            ['country_code' => 'CA', 'growth' => 4.77],
            ['country_code' => 'TT', 'growth' => 0],
        ],
        'group_name' => 'North America',
    ],
    [
        'countries' => [
            ['country_code' => 'BR', 'growth' => 2.19],
            ['country_code' => 'PE', 'growth' => 1.78],
            ['country_code' => 'UY', 'growth' => 8.83],
            ['country_code' => 'MX', 'growth' => 3.83],
        ],
        'group_name' => 'South America',
    ],
]

我想对每个国家/地区条目内的子数组进行排序(也许使用array_multisort),以便它们根据增长(最高的第一个)进行排序

排序后的数组将是:

[
    [
        'countries' => [
            ['country_code' => 'CA', 'growth' => 4.77],
            ['country_code' => 'US', 'growth' => 3.57],
            ['country_code' => 'TT', 'growth' => 0],
        ],
        'group_name' => 'North America',
    ],
    [
        'countries' => [
            ['country_code' => 'UY', 'growth' => 8.83],
            ['country_code' => 'MX', 'growth' => 3.83],
            ['country_code' => 'BR', 'growth' => 2.19],
            ['country_code' => 'PE', 'growth' => 1.78],
        ],
        'group_name' => 'South America',
    ],
]

最佳答案

最坏的情况是,您创建自己的排序函数并使用 usort .
它实际上是为这类事情而设计的。

就您而言,您将传递 $arr[$i]['countries'] 并让比较函数根据 $arr['growth'] 进行排序>.

关于php - 多维数组第四层中的第三层数据按列降序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11525320/

相关文章:

PHP 替换和小写

javascript - ajax插入数据库出错

php - Phalcon 持久型

用于矩阵的 python zip() 函数

javascript - 使用 for 循环追加数组

php - 无表搜索结果

c - 从数组中获取最大最小元素,删除它们并对数组的其余部分求和

arrays - 在 Ruby 中按字母顺序对数组内的数组进行排序?

database - 显示与搜索与数据库中的排序字符串

java - ArrayList 的对象排序使用可比较的