如何计算超过1个值

时间:2014-03-06 03:25:45

标签: php arrays count

$array = array(array('car1', 'car2'), 
array('car1', 'car2', 'car3'),
array('car1', 'car2', 'car3'));

我想要一个结果: [car1] [car2] = 3 [car1] [car2] [car3] = 2

2 个答案:

答案 0 :(得分:0)

迭代数组,然后再次迭代数组并将索引推送到数组中,但如果它们之前存在则递增值。

$count_values = array();
foreach ($array as $a) {
    foreach ($a as $b) {
        $count_values[$b]++;
    }
}

Working example

documentation for array_count_values内有这个答案,正如上面的评论所述。务必先检查文档。

答案 1 :(得分:0)

以下代码在php doc;

<?php

$ar1[] = array("red","green","yellow","blue");
$ar1[] = array("green","yellow","brown","red","white","yellow");
$ar1[] = array("red","green","brown","blue","black","yellow");
#$ar1= array("red","green","brown","blue","black","red","green"); // Possible with one     or multiple Array

$res = array_icount_values ($ar1);
print_r($res);

function array_icount_values($arr,$lower=true) {
     $arr2=array();
     if(!is_array($arr['0'])){$arr=array($arr);}
     foreach($arr as $k=> $v){
      foreach($v as $v2){
       if($lower==true) {$v2=strtolower($v2);}
       if(!isset($arr2[$v2])){
          $arr2[$v2]=1;
       }else{
          $arr2[$v2]++;
       }
     }
    }
    return $arr2;
 }
/*
Will print:
Array
(
    [red] => 3
    [green] => 3
    [yellow] => 4
    [blue] => 2
    [brown] => 2
    [white] => 1
    [black] => 1
)
*/
?>

link:http://cn2.php.net/manual/zh/function.array-count-values.php#95713