2013-07-10 136 views
0

我有以下陣列:計數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++;   
} 

林不太清楚如何處理呢?有人可以提出最佳做法嗎?

+1

在循環中使用if語句? – Neal

+0

保存一個地圖,其中每個事件值是關鍵字,值是計數。 –

回答

5
$counts = array(); 

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

print_r($counts); 
+0

謝謝!所以當我回聲$計數[$行動 - >事件];我得到[「Open」]值的總和。我如何獲得[「Click」]值的總和? – danyo

+1

'$ counts'是一個數組,因此請嘗試回顯'$ counts ['Click']''。 –

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

你打我吧.. :) –

+0

我會提供更正 'if(isset($ amount [$ actions [「Event」]]))$ amount [$ actions [「Event」]] ++;其他$金額[$動作[「事件」]] = 1;' – Trogvar

+0

改變它,謝謝。 –