首页 > 解决方案 > 在 PHP 中将两个 API 组合成一个数组

问题描述

希望从两个 API 端点获取数据并使用 PHP 将它们合并到一个数组中。

虽然我知道像 array_merge 这样的函数,但实际上并不是要附加数据,更像是在最后将它映射在一起。下面是我想要实现的一个例子。


$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;
}

标签: phpapidictionary

解决方案


这是它的功能

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

推荐阅读