bugfix> php > 投稿

値の出現回数に従ってPHPの配列をソートしたいです。

Array(Switzerland,Switzerland,Switzerland,Switzerland,Italy,Italy,Germany,France,France,France)

このような ...

Array(Switzerland,Switzerland, Switzerland,Switzerland,France,France,France,Italy,Italy,Germany,)

回答 2 件
  • PHP7の場合:

    <?php
    $couuntries = [
        'Switzerland',
        'Italy',
        'Switzerland',
        'France',
        'Switzerland',
        'Italy',
        'Germany',
        'France',
        'France',
        'Switzerland',
    ];
    $counts = array_count_values($couuntries);
    usort($couuntries, function($one, $second) use ($counts) {
        return $counts[$second] <=> $counts[$one];
    });
    print_r($couuntries);
    
    

    出力:

    Array
    (
        [0] => Switzerland
        [1] => Switzerland
        [2] => Switzerland
        [3] => Switzerland
        [4] => France
        [5] => France
        [6] => France
        [7] => Italy
        [8] => Italy
        [9] => Germany
    )
    
    

  • <?php
    $someArray = ['aa','aa','b','ccc','ccc','ccc'];
    $someArray = array_count_values($someArray); 
    arsort($someArray); 
    foreach($someArray as $key => $value) 
    {
       for ($i = 0; $i<$value; $i++) $result[] = $key; 
    }
    print_r($result);
    ?>
    
    

あなたの答え