mightyspaj3
mightyspaj3

Reputation: 471

Google PHP Client Library - invalid argument supplied for foreach()

Whenever the pageviews I am retrieving has 0 pageviews, I receive the error invalid argument supplied for foreach().

How am I supposed to prevent this error from occurring?

Here's my code:

        $parameters = array(
            'filters' => 'ga:pagePath==/about'
            'dimensions' => 'ga:pagePath',
            'metrics' => 'ga:pageviews,ga:uniquePageviews',
            'sort' => '-ga:pageviews'
        );

        $data = self::$analytics->data_ga->get(
            'ga:100174927',
            date("Y-m-d", $start),
            date("Y-m-d", $finish),
            'ga:visits',
            $parameters
        );

        $analytics = array(
            'pageviews'       => 0,
            'uniquePageviews' => 0
        );

        // This is the foreach loop that is creating the error:

        foreach ($data->getRows() as $key => $row)
        {    
            $analytics['pageviews']       += $row[1];
            $analytics['uniquePageviews'] += $row[2];
        }

        return $analytics;

Upvotes: 0

Views: 85

Answers (1)

Furhan S.
Furhan S.

Reputation: 1524

Do extensive checking like below:

if($data && is_array($data->getRows())){
    foreach ($data->getRows() as $key => $row)
    {    
        $analytics['pageviews']       += $row[1];
        $analytics['uniquePageviews'] += $row[2];
    }
}

$data may not be set in some cases causes foreach to complain.

Upvotes: 1

Related Questions