如何计算数组内数组中出现的值?

时间:2012-07-05 12:11:21

标签: php arrays multidimensional-array

如果我有以下数组:

 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'?

3 个答案:

答案 0 :(得分: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
)

答案 1 :(得分: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;
}

答案 2 :(得分: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