2011-03-26 31 views

回答

2

使用array_count_values($arr)。這將返回一個關聯數組,其中$arr中的每個值都用作鍵,該值的頻率爲$arr中的值。示例:

$arr = array(1, 2, 3, 4, 2); 
$counts = array_count_values($arr); 
$count_of_2 = $counts[2]; 
5

請參閱array_count_values()的文檔。這似乎是你在找什麼。

$array = array('a', 'b', 'c', 'a', 'b'); 
$counts = array_count_values($array); 
printf("Number of 'b's: %d\n", $counts['b']); 
var_dump($counts); 

輸出:

數量的「B的:2

陣列(3){
[ 「一」] => INT(2)
[ 「b」 的] => INT(2)
[ 「c」 的] => INT(1) }

+0

你能提供一個代碼中使用的例子嗎? – 2011-03-26 18:53:49

0

鋁儘管有一些奇特的方法,程序員應該能夠使用非常基本的編程操作員來解決這個問題。
知道如何使用循環和條件是絕對必要的。

$count = 0; 
$letters= array("a","b","c","a","b"); 
foreach ($letters as $char){ 
    if ($char == "b") $count = $count+1; 
} 
echo $count.' "b" found'; 

不是火箭科學。

1

您可以使用此功能計算實例的數量..

$b = array(a,b,c,a,b); 

function count_repeat($subj, $array) { 
    for($i=0;$i<count($array);$i++) { 
     if($array[$i] == $subj) { 
      $same[] = $array[$i]; //what this line does is put the same characters in the $same[] array. 
     } 
    return count($same); 
} 

echo count_repeat('b', $b); // will return the value 2