简体   繁体   中英

How to get count of same value in associative array in PHP

eg $arr:

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

I wants to get count of value-'win' here.

So in above example total counts are 3 for value 'win', because index d,e and f contain value 'win'.

You can have one variable to store the max and the current running continous win.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM