2012-07-05 65 views
0

如果我有下面的數組:如何計算陣列內ara數值的nb值?

Array ( 
     [0] => Array ([0] => 4555 [1] => 1) 
     [1] => Array ([0] => 4555 [1] => 1) 
     [2] => Array ([0] => 4350 [1] => 1) 
     [3] => Array ([0] => 4033 [1] => 2) 
     [4] => Array ([0] => 4159 [1] => 1) 
    ) 

我怎麼能算的出現「4555」中的Nb在大陣列內所有陣列存在?

回答

0

你需要兩個循環在另一個。就像這樣:

$counter = array(); 
for ($i = 0; $i < count($array); $i++) { 
    $subArray = $array [$i]; 
    for ($j = 0; $j < count ($subArray); $j++) { 
     $val = $subArray [$j]; 
     $count = isset ($counter [$val]) ? $counter [$val] : 0; 
     $counter [$val] = $count + 1; 
    } 
} 

,在這裏你可以打印$計數器值:

foreach ($counter as $k => $v) { 
    echo 'Count for ' . $k . ' is ' . $v; 
} 
+0

謝謝你,但我需要知道每一個值的計數,不僅4555, '4555' 就是一個例子。 – ZMajico 2012-07-05 12:27:41

+0

我已經根據新的要求更新了代碼 – 2012-07-05 12:33:27

0

您可以用array_reduce也做:

$arr = array ( 
     0 => array (0 => 4555, 1 => 1), 
     1 => array (0 => 4555, 1 => 1), 
     2 => array (0 => 4350, 1 => 1), 
     3 => array (0 => 4033, 1 => 2), 
     4 => array (0 => 4159, 1 => 1) 
    ); 

function f($x, $y){ 
     $x += in_array(4555, $y)?1:0; 
     return $x; 
} 
print array_reduce($arr, "f",0); 

OUTPUT:

2 
1

五月這可以幫助你:

<?php 
$a = Array (Array (4555,1), Array (4555,1),Array (4350,1),Array (4033,2),Array (4159,1 )); 

function array_keys_multi($array,&$vals) 
{ 
foreach ($array as $key => $value) { 

    if (is_array($value)) { 

     array_keys_multi($value,$vals); 

    }else{ 

     $vals[] = $value; 
    } 
} 

return $vals; 
} 

$z = array_keys_multi($a); 

print_r(array_count_values($z)); 
?> 

輸出:

Array 
(
[4555] => 2 
[1] => 4 
[4350] => 1 
[4033] => 1 
[2] => 1 
[4159] => 1 
)