从 Google Analytics 数据 API (GA4) 获取基于多个指标的数据。

6
我正在使用谷歌的数据 API 来获取来自指标和维度的不同类型的数据。但是对于某些情况,我的维度与日期相同,希望基于相同的维度获取多个指标。
以下是我的代码,我正在根据当前日期获取活跃用户。我想使用一个API报告获取多个指标,如活跃用户、新用户、会话,我必须调用下面的API 3次,通过传递不同的度量来获取数据。是否有其他的解决方案?
$property_id = 'PROPERTY-ID';
$client = new BetaAnalyticsDataClient();

$response = $client->runReport([
    'property' => 'properties/' . $property_id,
    'dateRanges' => [
        new DateRange([
            'start_date' => '2021-06-01',
            'end_date' => '2021-06-01',
        ]),
    ],
    'dimensions' => [new Dimension(
        [
            'name' => 'date',
        ]
    ),
    ],
    'metrics' => [new Metric(
        [
            'name' => 'activeUsers',
        ]
    )
    ]
]);


foreach ($response->getRows() as $row) {
    print $row->getDimensionValues()[0]->getValue()
        . ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL;
}

我已经尝试使用以下代码发送了两个指标:

'metrics' => [new Metric([
                'name' => 'activeUsers',
            ],[
                'name' => 'newUsers',
            ])]

我该如何从响应中提取数据?目前我使用以下方法进行提取:

foreach ($response->getRows() as $row) {
    print $row->getDimensionValues()[0]->getValue()
        . ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL;
}

使用$row->getMetricValues()[0]->getValue()可以返回activeUsers的值,但我如何获取newUsers的值呢?因为我使用了两个度量。我已经尝试过使用$row->getMetricValues()[1]->getValue(),但它没有起作用。

您可以在单个报告中放置多个指标。 - Linda Lawton - DaImTo
1
怎么办?我已经尝试过了,但它不起作用。并且我该如何使用下面的foreach循环来获取?我已经更新了问题,请现在检查。 - Asfandyar Khan
1个回答

2
这是一个具有2个维度和2个指标的API调用示例:
// Make an API call.
$response = $client->runReport([
    'property' => 'properties/' . $property_id,
    'dateRanges' => [
        new DateRange([
            'start_date' => '2022-06-16',
            'end_date' => 'today',
        ]),
    ],

    'metrics' => [
        new Metric([
            'name' => 'activeUsers',
        ]),
        new Metric([
            "name" => "sessions"
        ])
    ],
    'dimensions' => [
        new Dimension([
            "name" => "city"
        ]),
        new Dimension([
            'name' => 'firstUserSource',
        ])
    ],
]);

现在,在你的foreach循环中做这个:

    foreach ($response->getRows() as $row) {

    $return[] = [
        'city' => $row->getDimensionValues()[0]->getValue(),
        'source' => $row->getDimensionValues()[1]->getValue(),
        'users' => $row->getMetricValues()[0]->getValue(),
        'sessions' => $row->getMetricValues()[1]->getValue(),
    ];
}

然后只需将$return进行json_encode,就完成了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接