gremo
gremo

Reputation: 48909

Is there any way to check if a key exists in a nested array in PHP?

My result set come from a group/count query:

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

And it's in the form of an array nested into another array:

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)

Is there any way to easily check if a given type index exists without looping? For avoiding this:

$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;

Upvotes: 0

Views: 141

Answers (1)

curtisdf
curtisdf

Reputation: 4210

There's no way I'm aware of without looping. But you can re-index the SQL results into a format you like:

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

Upvotes: 1

Related Questions