简体   繁体   中英

counting foreach loop items

i have the following array:

[2]=>
  object(stdClass)#9 (4) {
    ["ID"]=>
    string(32) "43c845f895a56fbe8aea9435ef8fa806"
    ["Type"]=>
    string(8) "Campaign"
    ["Name"]=>
    string(28) "An unmissable invitation for"
    ["Actions"]=>
    array(5) {
      [0]=>
      object(stdClass)#10 (4) {
        ["Event"]=>
        string(4) "Open"
        ["Date"]=>
        string(19) "2013-05-07 17:00:00"
        ["IPAddress"]=>
        string(12) "109.239.93.2"
        ["Detail"]=>
        string(0) ""
      }
      [1]=>
      object(stdClass)#11 (4) {
        ["Event"]=>
        string(4) "Open"
        ["Date"]=>
        string(19) "2013-05-07 09:01:00"
        ["IPAddress"]=>
        string(12) "109.239.93.2"
        ["Detail"]=>
        string(0) ""
      }
      [2]=>
      object(stdClass)#12 (4) {
        ["Event"]=>
        string(4) "Open"
        ["Date"]=>
        string(19) "2013-04-30 22:29:00"
        ["IPAddress"]=>
        string(14) "94.171.192.216"
        ["Detail"]=>
        string(0) ""
      }
      [3]=>
      object(stdClass)#13 (4) {
        ["Event"]=>
        string(5) "Click"
        ["Date"]=>
        string(19) "2013-04-30 17:43:00"
        ["IPAddress"]=>
        string(12) "109.239.93.2"
        ["Detail"]=>
        string(60) "http://www.rbh.co.uk/rbhevent/?name=[fullname]&email=[email]"
      }
      [4]=>
      object(stdClass)#14 (4) {
        ["Event"]=>
        string(4) "Open"
        ["Date"]=>
        string(19) "2013-04-30 17:43:00"
        ["IPAddress"]=>
        string(12) "109.239.93.2"
        ["Detail"]=>
        string(0) ""
      }
    }
  }

i am trying to count the events that are the same. So for example ["Event"] = Open =4 / ["Event"] = Click =1.

I am trying to achieve this via counting a foreach loop:

$i=0;
foreach($entry->Actions as $actions ) { 
echo $i++;          
}

Im not quite sure how to approach this? Can someone suggest a best practice?

$counts = array();

foreach($entry->Actions as $actions) {
    if(!isset($counts[$actions->Event])) {
        $counts[$actions->Event] = 0;
    }
    ++$counts[$actions->Event];
}

print_r($counts);
<?php
$amounts = array(); // Events as key
foreach($entry->Actions as $actions)
{
    if (isset($amounts[$actions["Event"]])) $amounts[$actions["Event"]]++;
    else $amounts[$actions["Event"]] = 1;
}
print_r($amounts);
echo "<br>".$amounts["Open"];
?>

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