在多维数组中计数

时间:2012-11-16 14:20:27

标签: php arrays multidimensional-array counting

我有一个像这样的数组:

$resellers =  Array
(
    [40] => Array
        (
            [state] => AB
            [city] => Calgary
        )

    [185] => Array
        (
            [state] => AB
            [city] => Calgary
        )

    [141] => Array
        (
            [state] => AB
            [city] => Calgary
        )

    [41] => Array
        (
            [state] => AB
            [city] => Grande Prairie
        )

    [68] => Array
        (
            [state] => BC
            [city] => Burnaby
        )

    [51] => Array
        (
            [state] => BC
            [city] => Campbell River
        )

    [61] => Array
        (
            [state] => BC
            [city] => Kamloops
        )
  )

我想知道我是否有一个简单的方法可以计算出“Alberta”(将是4个)和BC(将是3个)有多少值。

4 个答案:

答案 0 :(得分:10)

array_count_values(array_map(function($item) {
   return $item['state'];
}, $resellers));

答案 1 :(得分:1)

只需遍历它即可找到您需要的状态。

function countState($data, $state) {
    $i = 0;
    foreach($data as $point)
        if($point['state'] === $state)
            $i++;

    return $i;
}

echo "Alberta found " . countState($array, "AB") . " times"!

答案 2 :(得分:0)

尝试:

$arr = array(array('state'=>'AB', 'city'=>'Calgary'), ...); //your array 

function count_values( $arr, $value) {
 $count = 0;
 foreach($arr as $v) {
  foreach($v as $m) {
   if( $m['state'] === $value )
    $count++;
  }
 }
 return $count;
}

$count_ab = count_values($arr, 'AB');
$count_bc = count_values($arr, 'BC');

答案 3 :(得分:0)

在Cedrun的回应帮助下解决。

内置阵列:

 $state_count = array_count_values( array_map(function($item){return $item['state'];}, $r_resellers));

然后输出:

echo $state_count["AB"];