Looping through the Google Analytics API PHP class data

Thanks for Jim Snyder from www.net-netanalytics.com for pointing out my examples were lacking the information to show how to loop through the resulting data from my Google Analytics API PHP Class. I have now update the examples file and also include the information about how to loop through the data in this post. You can always download the most recent version of my PHP class here.

The resulting array of data returned from the data() function is a multi dimensional array. The index(es) of the array are the dimensions passed in and then the value is another array with one vale for each of the metrics.

Looping through a single dimension

If, for example, you wanted to get the pagePath dimension and the pageviews and uniquePageviews metrics for pagePath, the data call would look like this:

$data = $api->data($id, 'ga:pagePath', 'ga:pageviews,ga:uniquePageviews');

You can then loop through the data like this:

foreach($data as $dimension => $metrics) {
     echo "$dimension pageviews: {$metrics['ga:pageviews']} unique pageviews: {$metrics['ga:uniquePageviews']}n";

Looping through two dimensions

This example gets the browser and version as the dimensions and then visits and pageviews as the metrics. This requires an outer loop and an inner loop. The data call looks like this:

$data = $api->data($id, 'ga:browser,ga:browserVersion', 'ga:visits,ga:pageviews', false, false, false, 100);

The loop looks like this:

foreach($data as $dimension1 => $array) {
 foreach($array as $dimension2 => $metrics) {
         echo "$dimension1 $dimension2 visits: {$metrics['ga:visits']} pageviews: {$metrics['ga:pageviews']}n";

And some of the resulting output looks like this:

Internet Explorer 7.0 visits: 13486 pageviews: 16232
 Internet Explorer 6.0 visits: 4823 pageviews: 5932
 Internet Explorer 8.0 visits: 3047 pageviews: 3805
 Internet Explorer 999.1 visits: 15 pageviews: 15

You could also access the pageviews value directly for Internet Explorer 8 like this:

echo $data['Internet Explorer']['8.0']['ga:pageviews'], "n";