0

我正在构建一个谷歌分析仪表板并且已经完成了,但我完全被这件真正让我挂断的事情难住了。

当我查询数据集的 GA Core Reporting API 时,我成功获得并能够显示结果,并且一切正常,除了我无法查询 JSON 对象的“start-index”。也就是说,它将显示的第一行(默认 = 1,但 GA 一次只返回 10k 行,因此如果您有一个超过 10k 行的数据集,这将变得至关重要!)。

为了尝试获取这个整数,我使用

$start = $results->query.start-index;

作为检查以确保我没有发疯,“max-results”就在 JSON 对象中的“start-index”旁边,这很好用:

$max = $results->totalResults;

这是 GA JSON 对象(根据https://developers.google.com/analytics/devguides/reporting/core/v3/reference#startIndex

{
"kind": "analytics#gaData",
 "id": string,
"selfLink": string,
"containsSampledData": boolean,
"query": {
  "start-date": string,
  "end-date": string,
  "ids": string,
  "dimensions": [
    string
  ],
  "metrics": [
    string
  ],
  "sort": [
    string
  ],
  "filters": string,
  "segment": string,
  "start-index": integer,
  "max-results": integer
},
"itemsPerPage": integer,
"totalResults": integer,
"previousLink": string,
"nextLink": string,
"profileInfo": {
  "profileId": string,
  "accountId": string,
  "webPropertyId": string,
  "internalWebPropertyId": string,
  "profileName": string,
  "tableId": string
},
"columnHeaders": [
  {
    "name": string,
    "columnType": string,
    "dataType": string
  }
],
"rows": [
  [
    string
  ]
],
"totalsForAllResults": [
  {
    metricName: string,
    ...
  }
]
}

帮助!提前致谢

4

2 回答 2

0

Property names in PHP can contain neither . nor -. Your code is interpreted as a string concatenation of an array with the result of a mathematical subtraction of two strings (don't even begin to try and understand this if you don't see what I mean from that description).

PHP is actually a complete pain in the rear-end when it comes to this point, you have to force it to convert the decoded data to associative arrays instead of objects by passing TRUE to the second argument of json_decode(). You can then access the data by array key:

E.g.

$results = json_decode($jsonString, TRUE);
$start = $results['query']['start-date'];
于 2012-08-14T14:02:37.350 回答
0

所以我仍然不完全确定为什么它会这样工作,但我已经使用以下函数成功地提取了正确的起始索引号:

function getStartIndex(&$results) {
  $query = $results->getQuery();

  foreach ($query as $paramName => $value) {
    if($paramName == "start-index")
    $startIndex = $value;
  }
  return $startIndex;
}

这实质上是遍历整个 $query 关联数组,直到找到参数与“start-index”匹配的数组,然后返回该值。

于 2012-08-14T15:30:45.753 回答