計數值出現在數組內的次數的最有效方法是什麼?PHP:針對數組的計數IF
實施例陣列(「蘋果」,「桔子」,「香蕉」,「香蕉」,「獼猴桃」)
最後,我想一個函數來吐出百分比圖表目的 (例如蘋果= 40%,香蕉= 40%,獼猴桃= 20%)
計數值出現在數組內的次數的最有效方法是什麼?PHP:針對數組的計數IF
實施例陣列(「蘋果」,「桔子」,「香蕉」,「香蕉」,「獼猴桃」)
最後,我想一個函數來吐出百分比圖表目的 (例如蘋果= 40%,香蕉= 40%,獼猴桃= 20%)
只要把它通過array_count_values
。百分比應該很容易......
$countedArray = array_count_values($array);
$total = count($countedArray);
foreach ($countedArray as &$number) {
$number = ($number * 100/$total) . '%';
}
<?php $array = array(1, "hello", 1, "world", "hello"); print_r(array_count_values($array)); ?>
上面的例子將輸出:
Array ( [1] => 2 [hello] => 2 [world] => 1 )
$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);
+1,然後使用'計數['apple'] * 100/count($ array)'以獲得百分比! – 2010-03-12 07:50:28