Thursday, 30 August 2018

Return a key from all elements of the associative array with mongodb and PHP

How can I get all the keys from within an associative array in a mongodb collection using the PHP driver.

Document:
[_id] => 1
[campaigns] => Array (
    [4e3b924d18153] => Array (
        [name] => Campaign One,
        [flag] => 1,
    ),
    [4e3b924d18154] => Array (
        [name] => Campaign Two,
        [flag] => 1,
    ),
    [4e3b924d18155] => Array (
        [name] => Campaign Three,
    ),
)

I need to get any flag fields from within the associative array campaigns. Flag may not necessarily exist.
Basically, I want to know which campaigns have the flag set.
I can use the following query, but it will return only the flag key for the first campaign
array('_id' => array('$in' => $projectIds)), array('campaigns.0.flag')

I would like to return the flag index for any campaign that is exists in.

if you need to do that with php the following lines should help you:
$flaged_compaigns = array();
foreach ($campaigns as $compaign->$data) {
    if (isset($data['flag']) and $data['flag']) {
        $flaged_compaigns[$compaign] = $data;
    }
}

0 comments:

Post a Comment