如何在PHP中的关联数组中获取相同值的计数

时间:2016-12-09 08:17:23

标签: php arrays

例如$ arr:

$arr = [
   'a' => [
              'key' => 'win'
          ],
   'b' => [
              'key' => 'loss'
          ],
   'c' => [
              'key' => 'loss'
          ],
   'd' => [
              'key' => 'win'
          ],
   'e' => [
              'key' => 'win'
          ],
   'f' => [
              'key' => 'win'
          ],
   'g' => [
              'key' => 'loss'
          ],
];

我想在这里得到值 - 'win'。

因此,在上面的示例中,值'win'的总计数为3,因为索引d,e和f包含值'win'。

1 个答案:

答案 0 :(得分:2)

您可以使用一个变量来存储最大值和当前运行的连续胜利。

$arr= array(
    "a" => array("key" => "win"),
    "b" => array("key" => "loss"),
    "c" => array("key" => "loss"),
    "d" => array("key" => "win"),
    "e" => array("key" => "win"),
    "f" => array("key" => "win"),
    "g" => array("key" => "loss")
);

$max = 0;
$count = 0;
foreach($arr as $value){
    if ($value["key"] == "win") $max = max(++$count, $max);
    else $count = 0;
}

var_dump($max);