Search code examples
phpadobe-analytics

How to check if JSON object exists


I made a post regarding a code for Adobe Analytics API. I am using a code to retrieve the first and second element (dimension) which is called 'breakdown'. The number varies depending on the data we have for this element.

I am using a loop with i=10 but I want to take everything. Which is the best way to achieve that?

I am using this code:

foreach ($json->report->data as $element) 
{
        // putting an excessive number for i
        for ($i=0;$i<100;$i++)
        {
            // checking if the object exists
            if (isset($element->breakdown[0]->breakdown[$i]->name)) 
            {
                echo $element->breakdown[0]->breakdown[$i]->name;

                // putting the data in a list I created before
                array_push($list, array(''.$element->year.'-'.$element->month.'-'.$element->day, $element->breakdown[0]->name, $element->breakdown[0]->breakdown[$i]->name, $element->breakdown[0]->breakdown[$i]->counts[0], $element->breakdown[0]->breakdown[$i]->counts[1]));
            }
            else
            {
                // Break the loop. All the objects are in the row. So, if there is not any for i=45 then there won't be any for i>45
                continue;
            }

        }
}

where I am trying to get all the objects. I am checking if the objects exist. If they don't, I want this loop to stop (second loop).


Solution

  • You can break the loop with break. for more information: http://php.net/manual/en/control-structures.break.php

    foreach ($json->report->data as $element) 
    {
        // putting an excessive number for i
        for ($i=0;$i<100;$i++)
        {
            // checking if the object exists
            if (isset($element->breakdown[0]->breakdown[$i]->name)) 
            {
                echo $element->breakdown[0]->breakdown[$i]->name;
    
                // putting the data in a list I created before
                array_push($list, array(''.$element->year.'-'.$element->month.'-'.$element->day, $element->breakdown[0]->name, $element->breakdown[0]->breakdown[$i]->name, $element->breakdown[0]->breakdown[$i]->counts[0], $element->breakdown[0]->breakdown[$i]->counts[1]));
            }
            else
            {
                // Break the loop. 
                break;
            }
    
        }
    

    }