具有多个具有相同名称的查询字符串参数的 Symfony HttpClient GET 请求

Symfony HttpClient GET request with multiple query string parameters with same name

我正在尝试按以下格式发出 API 请求:

/api/v1/courses?enrollment_state=active&include[]=total_students&include[]=term

如何使用 HttpClient 组件查询字符串参数来实现?

$response = $client->request('GET', '/api/v1/courses', [
      'query' => [
           'enrollment_state' => 'active',
           'include[]' => 'term',
           'include[]' => 'total_students',
       ],
]);

由于数组键重复,上述方法不起作用?

我也试过:

'include[]' => ['term', 'total_students']

创建等同于:

https://www.example.com/?token=foo&abc[]=one&abc[]=two

就这样:

$client->request(
    'GET',
    'https://www.example.com/',
    [
        'query' => [
            'token' => 'foo',
            'abc' => ['one', 'two']
        ]
    ]
);

如@user1392897 所说,@yivi 片段 returns 在 url 查询字符串中建立索引。

https://www.example.com/?foo[0]=bar&foo[1]=baz

那是因为它使用了 http_build_query 内置函数,这是函数行为。您可以阅读此线程 php url query nested array with no index

一种变通方法自己从数组中构建查询字符串并将其附加到 url,HttpClient->request() 方法的第二个参数.

function createQueryString(array $queryArray = []): ?string
{
    $queryString = http_build_query($queryArray, '', '&', \PHP_QUERY_RFC3986);
    $queryString = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '%5B%5D=', $queryString); //foo[]=x&foo[]=y
    
    return '' !== $queryString ? $queryString : null;
}

$queryArray = [
    'abc' => ['one', 'two']
];

$queryString = createQueryString($queryArray);

$url = 'https://www.example.com/';
if (is_string($queryString)) {
    $url = sprintf('%s?%s', $url, $queryString);
}

$response = $client->request('GET', $url);