从 Google Analytics Data API (GA4) 获取多个指标

问题描述 投票:0回答:2

我正在使用 Google 的数据 API 从指标和维度获取不同类型的数据。但在某些情况下,我的维度与日期相同,并且想要基于同一维度获取多个指标。

下面是我的代码,我根据当前日期获取 activeUsers。我想使用一个 API 报告获取多个指标,例如 activeUsers、newUsers、会话,我必须通过传递不同的指标来获取数据来调用下面的 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()
但不起作用。

google-analytics analytics google-analytics-api
2个回答
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(),
    ];
}

然后就

json_encode
$return
就这样了。


0
投票

嗨,在使用上面的代码时出现错误“警告:未定义的数组键 1 in”

© www.soinside.com 2019 - 2024. All rights reserved.