Leroy
Leroy

Reputation: 81

Combining two APIs into one array in PHP

Looking to take the data from two API endpoints and merge them into one array using PHP.

While I'm aware of functions like array_merge, not actually looking to append the data, more like map it together at the end. Below is an example of what I'm looking to achieve.;


$api1_endpoint = esc_url_raw( "http://api.com/endpoint" ); 
$api2_endpoint = esc_url_raw( "http://api.com/endpoint2" );

$api1 = json_decode( $api1_endpoint);
// {["sku"]=> string(12) "850661003403" ["productName"]=> string(16) "Product 1" ["productColor"]=> string(3) "red" }
$api2 = json_decode( $api2_endpoint);
// {["sku"]=> string(12) "850661003403" ["productName"]=> string(16) "Product 1" ["quantityAvailable"]=> float(5) }

$combined_apis = // function to combine $api1 and $api2 by ["sku"] or other key

foreach($combined_apis as $combined){
  echo $combined->sku;
  echo $combined->quantityAvailable;
}

Upvotes: 1

Views: 623

Answers (1)

Tosca
Tosca

Reputation: 453

Here is the function for that

public function combine_api_result($api1, $api2) {
    $output = $api1;
    foreach($api2 as $key => $value) {
        if ( ! isset($output[$key])) {
            $output[$key] = $value;
        }
    }
    return $output;
}

Upvotes: 2

Related Questions