使用以下代码(来自Analytics quickstart),我试图将维度和指标数据添加到$responseArray
数组中,以便稍后将其作为JSON返回:
public function formatDailySessionsReport( $reports ) {
$responseArray = array();
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++) {
//Adding dimension data here
$responseArray[$rowIndex][$i][$dimensionHeaders[$i]] = $dimensions[$i];
//print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
}
for ($j = 0; $j < count($metrics); $j++) {
$values = $metrics[$j]->getValues();
for ($k = 0; $k < count($values); $k++) {
$entry = $metricHeaders[$k];
//Adding metric data here
$responseArray[$j][$k][$entry->getName()] = $values[$k];
//print($entry->getName() . ": " . $values[$k] . "\n");
}
}
}
}
return $responseArray;
}
使用注释掉的
print
语句时,数据似乎可以正确打印:ga:date: 20170426
sessions: 2711
ga:date: 20170427
sessions: 2425
ga:date: 20170428
sessions: 2620
但是,当尝试将其添加到数组时,数据的格式似乎不正确(会话仅包含一次):
"response": [
[
{
"ga:date": "20170426",
"sessions": "656"
}
],
[
{
"ga:date": "20170427"
}
],
[
{
"ga:date": "20170428"
}
],
...
]
我正在使用以下内容来创建JSON响应:
$response = $this->formatDailySessionsReport( $reportData );
// Return response
echo json_encode( array( 'response' => $response ) );
我期待更多这样的事情:
"response" [
{
"ga:date": "20170426",
"sessions": "656"
},
{
"ga:date": "20170427",
"sessions": "1234"
},
{
"ga:date": "20170428",
"sessions": "1234"
}
]
连同日期和会话一起,如何构造
$responseArray
以获得期望的格式? 最佳答案
您可以将此代码与array_map()一起使用,
$responseArray['response'] = array_map(function($v){
return $v[0];
}, $responseArray['response']);