2013-03-24 29 views
-1

什麼是最好的方式來獲得數組中的前10個項目,我有一個數組有幾百個項目,我想從數組中使用PHP獲得前10個項目(最重複的項目),有什麼建議嗎?如何獲得數組(PHP)中的前10項?

+5

http://www.php.net/manual/en/function.array-count-values.php – SpacedMonkey 2013-03-24 03:04:08

+0

@SpacedMonkey哈哈,謝謝!我不知道爲什麼我沒有直接走了! : - / – 2013-03-24 03:56:49

回答

0

這應該做的伎倆:

$inputArray = array('orange','banana', 'banana', 'banana', 'pear', 'orange', 'apples','orange', 'grape', 'apple'); 

$countedArray = array_count_values($inputArray); 
arsort($countedArray); 

$topTen = array_slice($countedArray, 0, 10); 

以上將返回數組中最出現在項目的順序。

0

嘗試使用php的array_count_values()來獲取數組中每個值的出現次數,並與arsort()一起按最高頻率值對數組進行排序。然後,您可以使用array_slice()獲得陣列的前10個最常用值。

$dataArr = array('test', 4, 15.2, ...); // Input array with all data 
$frequencies = array_count_values($dataArr); 
arsort($frequencies); // Sort by the most frequent matches first. 
$tenFrequencies = array_slice($frequencies, 0, 10, TRUE); // Only get the top 10 most frequent 
$topTenValues = array_keys($tenFrequencies); 

注:我們需要使用array_keys()獲得最後的值,因爲array_count_values()「返回使用輸入數組作爲鍵的值以及它們在輸入作爲值頻率的數組。」

相關問題