按第三级列值对多维数组的第二级元素进行排序

问题描述 投票:0回答:3

我有下面的多维数组。

[
    2 => [
        66 => ['id' => 66, 'count' => 9],
        255 => ['id' => 255, 'count' => 20],
    ],
    1 => [
        59 => ['id' => 59, 'count' => 14],
        255 => ['id' => 255, 'count' => 73],
    ]
]

我想按 count 键的值按降序对内部数组进行排序。 我怎样才能实现它?

php arrays sorting multidimensional-array
3个回答
2
投票

尝试以下解决方案:

<?php
$array = Array
(
'2' => Array
    (
        '66' => Array
            (
                'id' => 66 ,                  
                'count' => 9
            ),
        '255' => Array
            (
                'id' => 255,                    
                'count' => 20
            )            

    ),

'1' => Array
    (
        '59' => Array
            (
                'id' => 59,                
                'count' => 14
            ),

        '255' => Array
            (
                'id' => 255,                   
                'count' => 73
            )
    )    
);

echo '<pre>';

foreach($array as &$ar){
usort($ar, function($a, $b) {
    return $b['count'] - $a['count'];
});
}

print_r($array);

输出:

Array
(
    [2] => Array
        (
            [0] => Array
                (
                    [id] => 255
                    [count] => 20
                )

            [1] => Array
                (
                    [id] => 66
                    [count] => 9
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [id] => 255
                    [count] => 73
                )

            [1] => Array
                (
                    [id] => 59
                    [count] => 14
                )

        )

)

0
投票

使用

uasort()
并通过引用进行修改,对数据子集进行
array_walk()
的迭代调用。

使用

$b
(三向比较运算符)时,将
$a
数据放在
<=>
数据之前,将进行 DESC 排序(
$a
$b
之前进行 ASC 排序)。

代码:(演示

$array = [
    2 => [
        66 => ['id' => 66, 'count' => 9],
        255 => ['id' => 255, 'count' => 20],
    ],
    1 => [
        59 => ['id' => 59, 'count' => 14],
        255 => ['id' => 255, 'count' => 73],
    ]
];

array_walk(
    $array,
    fn(&$set) => uasort($set, fn($a, $b) => $b['count'] <=> $a['count'])
);
var_export($array);

输出:

array (
  2 => 
  array (
    255 => 
    array (
      'id' => 255,
      'count' => 20,
    ),
    66 => 
    array (
      'id' => 66,
      'count' => 9,
    ),
  ),
  1 => 
  array (
    255 => 
    array (
      'id' => 255,
      'count' => 73,
    ),
    59 => 
    array (
      'id' => 59,
      'count' => 14,
    ),
  ),
)

-1
投票

这是一个例子:

在 PHP 中按值对多维数组进行排序 https://paulund.co.uk/sort-multi-Dimension-array-value

© www.soinside.com 2019 - 2024. All rights reserved.