【问题标题】:counting foreach loop items计算 foreach 循环项目
【发布时间】:2013-07-10 13:16:42
【问题描述】:

我有以下数组:

[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"] = 打开 =4 / ["Event"] = 点击 =1。

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

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

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

【问题讨论】:

  • 在循环中使用 if 语句?
  • 保留一个映射,其中每个事件值是键,值是计数。

标签: php foreach


【解决方案1】:
$counts = array();

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

print_r($counts);

【讨论】:

  • 谢谢!所以当我回显 $counts[$actions->Event];我得到了 ["Open"] 值的总数。我如何获得 ["Click"] 值的总数?
  • $counts 是一个数组,所以尝试回显$counts['Click']
【解决方案2】:
<?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"];
?>

【讨论】:

  • 我会提供更正if (isset($amounts[$actions["Event"]])) $amounts[$actions["Event"]]++; else $amounts[$actions["Event"]] = 1;
猜你喜欢
  • 2014-03-03
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
  • 2016-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多