如何在阵列中找到最常见的重复项?

Edw*_*uay 0 php arrays

getMostFrequentlyOccurringItem()下面创建函数的最佳方法是什么?

//should return "paragraph"
echo getMostFrequentlyOccurringItem(array('line', 'paragraph', 'paragraph'));

//should return "line"
echo getMostFrequentlyOccurringItem(array('wholeNumber', 'line', 'line', 'line'));

//should return null
echo getMostFrequentlyOccurringItem(array('wholeNumber', 'wholeNumber', 'paragraph', 'paragraph'));

//should return "wholeNumber"
echo getMostFrequentlyOccurringItem(array('wholeNumber', '', '', ''));

function getMostFrequentlyOccurringItem($items) {
    //...
}
Run Code Online (Sandbox Code Playgroud)

回答:

谢谢亚当,这是我完成的解决方案:http: //tanguay.info/web/index.php?pt = codeExamples&id = 396

Ann*_*rom 8

首先array_count_values(),按照您的喜好按摩输出.

php> =array_count_values(array('wholeNumber', 'line', 'line', 'line'))
array(
  "wholeNumber" => 1,
  "line" => 3,
)
Run Code Online (Sandbox Code Playgroud)

arsort($counts, SORT_NUMERIC)array_count_values()首先按频率对输出进行排序.

  • Mh,ksort()按键排序,键是单词,因此,使用sort()函数按出现次数排序是不是更好? (2认同)