按键值排序php多维数组

时间:2016-05-25 07:31:25

标签: php arrays sorting multidimensional-array

我有以下的multidimesional数组。

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
            )
    )    
)

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

感谢。

2 个答案:

答案 0 :(得分: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
                )

        )

)

答案 1 :(得分:0)

以下是一个例子:

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