2012-05-23 45 views
0

我的結果集來自一組/數查詢:有什麼辦法來檢查一個鍵是否存在於PHP中的嵌套數組中?

SELECT m.type, COUNT(m.type) 
FROM sent_message m 
WHERE m.user_id = :user_id 
     AND (m.sent_at >= :start_date OR m.sent_at <= :end_date) 
GROUP BY m.type 

而且它在 數組嵌套到另一個數組形式:

array (size=2) 
    0 => 
    array (size=2) 
     'type' => string 'sms' (length=3) 
     'count' => string '1' (length=1) 
    1 => 
    array (size=2) 
     'type' => string 'email' (length=5) 
     'count' => string '9' (length=1) 

有沒有什麼辦法,如果能夠容易地檢查給定type索引存在沒有循環?爲了避免這種情況:

$resultSet = $repository->getAllCount(); // Returns the nested array 
$viewBag = array('sent_sms_count' => 0, 'sent_email_count' => 0); // Init 

foreach($resultSet as $result) : 

    if('sms' == strtolower($result['type']) 
     $viewBag['sent_sms_count'] = $result['count']; 

    if('email' == strtolower($result['type']) 
     $viewBag['sent_email_count'] = $result['count']; 

endforeach; 
+1

完全重複的http://stackoverflow.com/questions/1019076/how-to-search-by-key-value-in-一個-多維陣列式的PHP –

回答

1

我沒有辦法知道沒有循環。但是,您可以將SQL結果重新索引爲您喜歡的格式:

foreach ($resultSet as $result) { 
    $viewBag['sent_' . strtolower($result['type']) . '_count'] = $result['count']; 
} 
相關問題