php - 在 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;
}
解决方案
这是它的功能
public function combine_api_result($api1, $api2) {
$output = $api1;
foreach($api2 as $key => $value) {
if ( ! isset($output[$key])) {
$output[$key] = $value;
}
}
return $output;
}
推荐阅读
- github - 如何在 git 存储库中维护 CMake 项目的构建目录?
- excel - 在 Oracle OBIEE 中将查询和过滤变量附加到输出
- ffmpeg - 有没有办法使用 Ffmpeg 从.webm 中剪切前 1 秒的视频而没有关键帧?
- javascript - 自定义滚动条,像引力透镜一样围绕拇指灵活扩展轨道
- tensorflow - 无法使用 DenseFeature 输入层构建模型,得到“'DenseFeatures' 对象没有属性 'shape'”
- c - 在 C 中动态分配具有 10 亿个元素的整数数组
- kubernetes - 如何在 Kubernetes 中包含多个文件和文件夹的 pod 文件夹中挂载特定文件
- prometheus - Prometheus Alertmanger 使用 curl 删除所有静音。REST API
- java - 将集合转换为 csv 元素的列表 Java 8
- typescript - 键入一个变量作为地图中的任何键?