我的结果集来自一个组/计数查询:
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;
答案 0 :(得分:1)
如果没有循环,我无法意识到。但是您可以将SQL结果重新索引为您喜欢的格式:
foreach ($resultSet as $result) {
$viewBag['sent_' . strtolower($result['type']) . '_count'] = $result['count'];
}