如何将多次API请求结果合并为单个PHP数组?
问题:合并多次API调用结果为一维数组
我通过以下方式多次调用API:
foreach ($pickResults as $data) { $api = Http::asForm()->post('https://www.pxxxxxxx.com/apis/xxxxxx', [ 'query' => $data, ]); }
每次API调用返回的结果格式如下:
{ "query": "on the server to successfully complete the installation if you want to update the laravel framework you may issue the php composer", "totalMatches": 2, "websites": [ { "title": "How to setup laravel framework in wampserver properly?", "desc": "3.1. Open a command-line interface (cmd). 3.2. Go to the directory in which you want to install Laravel. This is usually your development directory. In this tutorial, we’ll use C:\\wamp\\www\\laravel. 3.3. Instruct Composer to install Laravel into a project directory. We use project name myproject.", "url": "https://stackoverflow.com/questions/20984148/how-to-setup-laravel-framework-in-wampserver-properly" }, { "title": "Installation - Laravel - The PHP Framework For Web Artisans", "desc": "Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.", "url": "https://laravel.com/docs/4.2" } ] }
我需要将所有API返回的结果合并成一个一维数组,格式如下:
[{ "title": "", "desc": "", "url": "" }, { "title": "", "desc": "", "url": "" }, { "title": "", "desc": "", "url": "" }]
我尝试了以下代码,但得到的是多维数组,不是目标格式:
$response = array(); foreach ($pickResults as $data) { $api = Http::asForm()->post('https://www.pxxxxxxx.com/apis/xxxxxx', [ 'query' => $data, ]); $response[] = $api["websites"]; }
请问该如何解决?
解决方案
你当前的代码是把每个API返回的websites数组直接追加到$response里,所以会形成多维数组($response的每个元素都是一个数组)。要合并成一维数组,需要把websites里的每个元素单独整合到总结果中,以下是两种可行的实现方式:
方式一:遍历子数组逐个追加
修改代码,在获取到$api["websites"]后,再遍历这个子数组,把每个站点元素单独添加到$response:
$response = array(); foreach ($pickResults as $data) { $api = Http::asForm()->post('https://www.pxxxxxxx.com/apis/xxxxxx', [ 'query' => $data, ]); // 遍历当前API返回的站点列表,逐个追加到总结果 foreach ($api["websites"] as $site) { $response[] = $site; } }
方式二:用array_merge合并数组
如果$api["websites"]是索引数组,可以用array_merge直接将当前站点数组与总数组合并:
$response = array(); foreach ($pickResults as $data) { $api = Http::asForm()->post('https://www.pxxxxxxx.com/apis/xxxxxx', [ 'query' => $data, ]); // 合并当前站点数组到总结果 $response = array_merge($response, $api["websites"]); }
这两种方式都能得到你需要的一维数组,第一种逻辑更直观,第二种适合处理纯索引数组的场景。
内容的提问来源于stack exchange,提问作者Benny
相关产品推荐
相关产品推荐

