2010-03-12 38 views
4

計數值出現在數組內的次數的最有效方法是什麼?PHP:針對數組的計數IF

實施例陣列(「蘋果」,「桔子」,「香蕉」,「香蕉」,「獼猴桃」)

最後,我想一個函數來吐出百分比圖表目的 (例如蘋果= 40%,香蕉= 40%,獼猴桃= 20%)

回答

3

只要把它通過array_count_values。百分比應該很容易......

$countedArray = array_count_values($array); 
$total = count($countedArray); 

foreach ($countedArray as &$number) { 
    $number = ($number * 100/$total) . '%'; 
} 
+2

+1,然後使用'計數['apple'] * 100/count($ array)'以獲得百分比! – 2010-03-12 07:50:28

2

使用array_count_values()

<?php 
$array = array(1, "hello", 1, "world", "hello"); 
print_r(array_count_values($array)); 
?> 

上面的例子將輸出:

Array 
(
    [1] => 2 
    [hello] => 2 
    [world] => 1 
) 
0
$a = Array ('apple','apple','banana','banana','kiwi'); 
$b = array_count_values($a); 
function get_percentage($b,$a){ 
    $a_count = count($a); 
    foreach ($b as $k => $v){ 
     $ret[$k] = $v/$a_count*100."%"; 
    } 
    return $ret; 
} 
$c = get_percentage($b,$a); 
print_r($c);