2015-07-10 71 views
0

每當我檢索的綜合瀏覽量有0個綜合瀏覽量時,我收到錯誤invalid argument supplied for foreach()Google PHP客戶端庫 - 爲foreach提供的無效參數()

我該如何防止這種錯誤發生?

這裏是我的代碼:

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

回答

1

做廣泛的檢查象下面這樣:

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

$數據可能無法在某些情況下,可以設置導致的foreach抱怨。