0

如果我有以下数组:

 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 ) 
      )

我如何计算大数组内的所有数组中出现的 Nb '4555'?

4

3 回答 3

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
)
于 2012-07-05T12:34:56.090 回答
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;
    }
}

在这里您可以打印 $counter 值:

foreach ($counter as $k => $v) {
   echo 'Count for ' . $k . ' is ' . $v;
}
于 2012-07-05T12:16:06.553 回答
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);

输出:

2
于 2012-07-05T12:24:04.383 回答