2010-02-01 63 views

回答

13

PHP實際上提供了一些方便array functions你可以用它來實現這一目標。

實施例:

<?php 
$arr = array(
    'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 
    'orange', 'orange', 'orange', 
    'banana', 'banana', 'banana', 'banana', 'banana', 
    'pear', 'pear', 'pear', 'pear', 'pear', 'pear', 'pear', 
    'grape', 'grape', 'grape', 'grape', 
    'melon', 'melon', 
    'etc' 
); 

$reduce = array_count_values($arr); 
arsort($reduce); 
var_dump(array_slice($reduce, 0, 5)); 

// Output: 
array(5) { 
    ["pear"]=>  int(7) 
    ["apple"]=>  int(6) 
    ["banana"]=> int(5) 
    ["grape"]=>  int(4) 
    ["orange"]=> int(3) 
} 

EDIT:添加array_slice,如下面阿利克斯的交使用。

1

構建計數的數組,並把它們以相反的順序:

$mode = array_count_values($input); 
arsort($mode); 
$i = 0; 
foreach ($mode as $k => $v) { 
    $i++; 
    echo "$i. $k occurred $v times\n"; 
    if ($i == 5) { 
    break; 
    } 
} 
+0

你的徽章數量是太酷了...... 12,2^7 - 1,2^8 + 1! – 2010-02-01 13:26:41

7

在這裏你去:

$yourArray = array(1, "hello", 1, "world", "hello", "world", "world"); 
$count = array_count_values($yourArray); 

arsort($count); 

$highest5 = array_slice($count, 0, 5); 

echo '<pre>'; 
print_r($highest5); 
echo '</pre>'; 
+0

+1'array_slice' – Matt 2010-02-01 13:04:12

+0

@Matt:謝謝,當我發佈我的答案時,我沒有意識到你已經在使用'array_count_values()'函數。 – 2010-02-01 13:12:04