首页 > 解决方案 > 通过 Laravel Http Client 发送嵌套数组

问题描述

我想通过 Laravel Http Client (Laravel 7.x) 向包含嵌套参数的 API 网站发送请求

$params = [
   'type' => 'books',
   'variables' => [
      'color' => 'red',
      'size' => 'large'
   ]
]

我希望我的网址喜欢这样:

http://example.com/?type=books&variables={"color":"red","size":"large"}

编码以上网址:

http://example.com/?type=books&variables=%7B%22color%22%3A%22red%22%2C%22size%22%3A%22large%22%7D

但是当我使用:

Http::get('http://example.com', $params);

API 服务器返回错误。

但是当我使用:

Http::get('http://example.com/?type=books&variables={"color":"red","size":"large"}');

它运作良好。

那么如何将我的 params 数组转换为 url 呢?

(我无权访问 API 服务器)

标签: laravelhttphttpclientguzzle

解决方案


尝试json_encode()

 $params = [
            'type' => 'books',
            'variables' => json_encode([
               'color' => 'red',
               'size' => 'large'
            ])
         ]

$url = "http://example.com?".http_build_query($params);

Http::get($url);

http_build_query() 参考链接https://www.php.net/manual/en/function.http-build-query.php


推荐阅读