PHP: Most frequent value in array

后端 未结 2 558
执笔经年
执笔经年 2020-12-03 14:21

So I have this JSON Array:

[0] => 238
[1] => 7
[2] => 86
[3] => 79
[4] => 55
[5] => 92
[6] => 55
[7] => 7
[8] => 254
[9] => 9
[         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 14:59

    The key is to use something like array_count_values() to tally up the number of occurrences of each value.

     count) pairs, sorted by descending count
    $counts = array_count_values($array);
    arsort($counts);
    // array(238 => 3, 55 => 2, 7 => 2, 75 => 1, 89 => 1, 9 => 1, ...)
    
    // An array with the first (top) 5 counts
    $top_with_count = array_slice($counts, 0, 5, true);
    // array(238 => 3, 55 => 2, 7 => 2, 75 => 1, 89 => 1)
    
    // An array with just the values
    $top = array_keys($top_with_count);
    // array(238, 55, 7, 75, 89)
    
    ?>
    

提交回复
热议问题