使用PHP的google analytics api v4。订购输出

时间:2016-06-28 10:26:25

标签: php google-analytics-api google-api-php-client

我在使用PHP的谷歌分析API v4上有这个代码。

  $eCPM_Adsense = new Google_Service_AnalyticsReporting_Metric();
  $eCPM_Adsense->setExpression("ga:adsenseECPM");
  $eCPM_Adsense->setAlias("eCPM Adsense");


    // Create the Ordering.
    $ordering = new Google_Service_AnalyticsReporting_OrderBy();
    $ordering->setFieldName("ga:adsenseECPM");
    $ordering->setOrderType("VALUE");   
    $ordering->setSortOrder("DESCENDING");

订购对我不起作用。你能帮助我吗? 感谢

3 个答案:

答案 0 :(得分:20)

问题是您需要在请求中使用setOrderBys()。这在API文档中没有详细说明......

一个例子

$ordering = new Google_Service_AnalyticsReporting_OrderBy();
$ordering->setFieldName("ga:pageviews");
$ordering->setOrderType("VALUE");   
$ordering->setSortOrder("DESCENDING");

$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setDimensions(array($path));
$request->setMetrics(array($sessions));
$request->setOrderBys($ordering); // note this one!

答案 1 :(得分:1)

OrderBy 方法在 Google 文档中没有很好地解释。 他们在 Reporting API v4 中的唯一示例是

// Create the Ordering.
$ordering = new Google_Service_AnalyticsReporting_OrderBy();
$ordering->setOrderType("HISTOGRAM_BUCKET");
$ordering->setFieldName("ga:sessionCount");

这里是一个 getReport($analytics) 的例子

function getReport($analytics) {

  // Replace with your view ID, for example XXXX.
  $VIEW_ID = "<REPLACE_WITH_VIEW_ID>";

  // Create the DateRange object.
  $dateRange = new Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate("30daysAgo");
  $dateRange->setEndDate("yesterday");

  // Create the Metrics object.
  $sessions = new Google_Service_AnalyticsReporting_Metric();
  $sessions->setExpression("ga:searchUniques");
  $sessions->setAlias("searchKeyword");

  //Create the Dimensions object.
  $searchKeyword = new Google_Service_AnalyticsReporting_Dimension();
  $searchKeyword->setName("ga:searchKeyword");

  // Create order object
  $ordering = new Google_Service_AnalyticsReporting_OrderBy();
  $ordering->setFieldName("ga:searchUniques");
  $ordering->setOrderType("VALUE");   
  $ordering->setSortOrder("DESCENDING"); //There is no "-" usage

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId($VIEW_ID);
  $request->setDateRanges($dateRange);
  $request->setDimensions(array($searchKeyword));
  $request->setMetrics(array($sessions));
  $request->setOrderBys($ordering); //Must be added

  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  return $analytics->reports->batchGet( $body );
}

迁移文档中也没有提及。希望快点更新。

答案 2 :(得分:0)

我创建了一个库,可以帮助您轻松地使用php集成分析api v4。看看:https://github.com/panakour/google-analytics