向 YouTube 发送请求时出现奇怪错误 API PHP

Weird error while sending request to YouTube API PHP

我目前正在进行后端处理,请求从 PHP 上的 YouTube Analytics API 返回频道分析信息。出于某种原因,我不断收到一条奇怪的错误消息:

foreach ($metrics as $metric) {
$api = $analytics->reports->query($id, $start_date, $end_date, $metric, $optparams);
print('reached');
    foreach ($api->rows as $r) {
        print($r[0]);
        print($r[1]);
    }
}

Fatal error: Uncaught TypeError: array_merge(): Argument #2 must be of type array, string given in ... 

所以我假设错误与 $query 相关并且输入应该是数组类型所以我这样做了:

foreach ($metrics as $metric) {
$params = [$id, $start_date, $end_date, $metric, $optparams];
$api = $analytics->reports->query($params);
print('reached');
    foreach ($api->rows as $r) {
        print($r[0]);
        print($r[1]);
    }
}

Fatal error: Uncaught Google\Exception: (query) unknown parameter: '0'

但是如您所见,错误仍然存​​在。对于第二个,我假设因为 PHP 中的数组在技术上是顺序映射,这就是为什么它与 '0' 一致,但我仍然很困惑为什么它会在无法处理它的情况下要求一个数组.

有关我的代码的更多上下文,我正在使用 Google API 的 PHP 客户端库,这是我通过 composer require google/apiclient:^2.0 获得的。这是我实例化所有对象的整个代码文件:

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  // Set the access token on the client.
  $client->setAccessToken($_SESSION['access_token']);

  // Create an authorized analytics service object.
  $analytics = new Google_Service_YouTubeAnalytics($client);

} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/Analytics_Dashboard/oauth2callbackYouTube.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

// here we set some params
$id = '////////';
$end_date = date("Y-m-d"); 
$start_date = date('Y-m-d', strtotime("-30 days"));
$optparams = array(
    'dimensions' => '7DayTotals',
    'sort' => 'day',
);

$metrics = array(
    'views',
    'estimatedMinutesWatched',
    'averageViewDuration',
    'comments',
    'favoritesAdded',
    'favoritesRemoved',
    'likes',
    'dislikes',
    'shares',
    'subscribersGained',
    'subscribersLost'
);

$api_response = $metrics;

// You can only get one metric at a time, so we loop
foreach ($metrics as $metric)
{
    $params = [$id, $start_date, $end_date, $metric, $optparams];
    $api = $analytics->reports->query($params);
    // if (isset($api['rows'])) $api_response[$metric] = $api['rows'][0][0];
    print('reached');
    foreach ($api->rows as $r) {
        print($r[0]);
        print($r[1]);
    }
}

感谢曾使用 PHP 与 YouTube 分析 API 进行交互的人提供的任何帮助!谢谢!

我不确定这是否可行,但是如果您使用关联数组而不是常规数组呢?

    $params = [$id, $start_date, $end_date, $metric, $optparams]; //OLD
    $params = [ 
       'id' => $id, 
       'start_date' => $start_date, 
       'end_date' => $end_date, 
       'metric' => $metric, 
       'opt_params' => $optparams
     ];

万一有效,你想使用 compact,只是为了更短的语法:

    $params = compact('id', 'start_date', 'end_date', 'metric', 'opt_params');