gpt4 book ai didi

php - 将维度和指标数据添加到数组

转载 作者:行者123 更新时间:2023-12-03 15:56:16 27 4
gpt4 key购买 nike

使用以下代码(来自 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

但是,当尝试将其添加到数组时,数据的格式似乎不正确( session 仅包含一次):
"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"
}
]

将日期和 session 包含在一起, 我如何构建 $responseArray得到我预期的格式?

最佳答案

您可以将此代码与 array_map() 一起使用,

$responseArray['response'] = array_map(function($v){
return $v[0];
}, $responseArray['response']);

关于php - 将维度和指标数据添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44196932/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com