计算foreach循环项目

时间:2013-07-10 13:16:43

标签: php foreach

我有以下数组:

[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) ""
      }
    }
  }

我正在尝试计算相同的事件。例如,[“Event”] = Open = 4 / [“Event”] = Click = 1。

我试图通过计算foreach循环来实现这一点:

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

我不太确定如何处理这个问题?有人可以提出最佳做法吗?

2 个答案:

答案 0 :(得分:5)

$counts = array();

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

print_r($counts);

答案 1 :(得分:4)

<?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"];
?>