2010-02-01 12 views

risposta

13

PHP in realtà un po 'a portata di mano array functions è possibile utilizzare per raggiungere questo obiettivo.

Esempio:

<?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: Inserito array_slice, come usato nel post di Alix sotto.

1

Costruire la matrice di conteggi e metterli in ordine inverso: fornisce

$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

Il tuo numero di badge è così cool ... 12, 2^7-1, 2^8 + 1! –

7

Qui si va:

$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 per 'array_slice' – Matt

+0

@Matt: Grazie, quando ho postato la mia risposta non mi sono reso conto che stavate già usando la funzione' array_count_values ​​() '. –

Problemi correlati