【问题标题】:Symfony HttpClient GET request with multiple query string parameters with same nameSymfony HttpClient GET 请求具有多个具有相同名称的查询字符串参数
【发布时间】:2020-02-27 19:47:49
【问题描述】:

我正在尝试按以下格式发出 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']

【问题讨论】:

  • 您是否尝试过仅使用一个“包含”键并在数组中传递“学期”和“总学生”?

标签: php symfony symfony4 symfony-http-client


【解决方案1】:

创建等价于:

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

只要做:

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

【讨论】:

【解决方案2】:

正如@user1392897 所说,@yivi sn-p 在 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-11
    • 2021-12-07
    • 1970-01-01
    • 2016-02-04
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多