2
votes

I am using Google API V4 https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-php

I am having issue with setAlias function. When there are multiple metrics selected, all the returned headers are same.

Code:

   <?php
    $metrices = {FORM ARRY WITH MULTIPLE METRICES} 
       $nmetrices = array();
        if(is_array($metrices) && count($metrices) > 0){
          $i=0;
          foreach($metrices as $metric){
            $nmetrices[$i] = new     Google_Service_AnalyticsReporting_Metric();
            $nmetrices[$i]->setExpression($metric);
            $nmetrices[$i]->setAlias($metric);
            $i+=1;
          }
        }?>

Example:

I have selected "ga:users" and "ga:percentNewSessions", but the returned results have title: "ga:users" for both metrics.

ga:medium: (none)
ga:date: 20150810
Metric type: INTEGER
**ga:users: 764
ga:users: 97.38219895287958**
ga:medium: (none)
ga:date: 20150811
Metric type: INTEGER
**ga:users: 2495
ga:users: 85.50284629981024**
1

1 Answers

1
votes

I just started on Analytics API v4 and came across this problem. The provided PHP code doesn't allow for multiple metrics for the printResults() function in the example, however the data from Google contains the correct alias.

The metrics object from google is a single root however the metrics header object is a separate entry per requested metric type.

Here's an updated printResults() function that will cater for multiple metrics.

function printResults($reports) {
    for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
        $report = $reports[ $reportIndex ];
        $header = $report->getColumnHeader();
        $dimensionHeaders = $header->getDimensions();
        $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
        $rows = $report->getData()->getRows();

        for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
            $row = $rows[ $rowIndex ];
            $dimensions = $row->getDimensions();
            $metrics = $row->getMetrics();
            for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
                print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
            }

            for ($j = 0; $j < count( $metricHeaders ); $j++) {
                $entry = $metricHeaders[$j];
                $values = $metrics[$rowIndex];
                $value = $values->getValues()[$j];
                print($entry->getName() . ": " . $value . "\n");
            }
        }
    }
}