Home > Software design >  Merging the results of an API response into a single php array
Merging the results of an API response into a single php array

Time:10-15

I am doing multiple calls to an api like this

            foreach ($pickResults as $data) {
                $api = Http::asForm()->post('https://www.pxxxxxxx.com/apis/xxxxxx', [
                    'query' => $data,
                ]);

            }

This is the kind of result I am getting from each $api calls:

{
  "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"
    }
  ]
}

I would like to merge all like this as a single array:

[{
"title"
"desc"
"url"
},
{
"title"
"desc"
"url"
},
{
"title"
"desc"
"url"
}],

I am really struggling with this.

I tried this:

           
 $response = array();
 foreach ($pickResults as $data) {
$api = Http::asForm()->post('https://www.pxxxxxxx.com/apis/xxxxxx', [
              'query' => $data,
                ]);
             $response[] = $api["websites"];
}

But it is giving me the result into a multidimensional array rather than merging everything.

Any idea how to solve this issue, please?

Thanks all!

CodePudding user response:

Try using json_decode($json, $associative) function to convert your response to an associative array like :

$response = json_decode($api, true); 
$websites = $response["websites"]

https://www.php.net/manual/en/function.json-decode.php

CodePudding user response:

I'm assuming that you are sening multiple requests and you want to merge all their results. Here's one way it could be done:

$result = [];

foreach ($pickResults as $data) {
    $api = Http::asForm()->post('https://www.pxxxxxxx.com/apis/xxxxxx', [
        'query' => $data,
    ]);
    $result = array_merge($result, $api["websites"]);
}
  •  Tags:  
  • php
  • Related