PHP Sort a multidimensional array by number of items

后端 未结 3 1979
予麋鹿
予麋鹿 2020-12-09 15:28

I have an array such as:

Array
(
    [DEF] => Array
        (
            [0] => Array
                (
                    [type] => 1
                    


        
相关标签:
3条回答
  • 2020-12-09 16:17

    Using uksort:

    uksort($array, function($a, $b) { return count($b) - count($a); });
    

    Using array_multisort:

    array_multisort(array_map('count', $array), SORT_DESC, $array);
    

    With PHP < 5.3:

    function sort_cb($a, $b) {
        return count($b) - count($a);
    }
    uksort($array, 'sort_cb');
    
    0 讨论(0)
  • 2020-12-09 16:23
    $tempArr = $sortedArr = array();
    foreach ($myArr as $k => $v) $tempArr[$k] = count($v);
    asort($tempArr);
    foreach ($tempArr as $k => $v) $sortedArr = $myArr[$k];
    

    Note that this will break if any of the array values are not themselves arrays, you may want to add an is_array() check somewhere...

    0 讨论(0)
  • 2020-12-09 16:24
    <?php
    function cmp($a, $b)
    {
        if ($a == $b) {
            return 0;
        }
        return (count($a) > count($b)) ? -1 : 1;
    }
    
    $a = array(
    "AA" => array(
            array('type'=>'1', 'id'=>'2'),
            array('type'=>'2', 'id'=>'2')),
    'BB' => array(
            array('type'=>'1', 'id'=>'2'),
            array('type'=>'2', 'id'=>'2'),
            array('type'=>'5', 'id'=>'2')),
    'CC' => array(
            array('type'=>'1', 'id'=>'2'))
    );  
    
    usort($a, "cmp");
    
    print_r($a);
    ?>
    
    0 讨论(0)
提交回复
热议问题