0

我有一个像这样的数组:

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

我想知道是否有一种简单的方法可以计算“阿尔伯塔”(即 4)和 BC(即 3)的值。

4

4 回答 4

11
array_count_values(array_map(function($item) {
   return $item['state'];
}, $resellers));
于 2012-11-16T14:26:09.233 回答
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"!
于 2012-11-16T14:28:57.100 回答
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');
于 2012-11-16T14:23:56.823 回答
0

在 Cedrun 的回应的帮助下解决了。

内置数组:

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

然后输出:

echo $state_count["AB"];
于 2012-11-16T14:52:14.333 回答