在 PHP 中合并 2 Json 个文件

Merge 2 Json file in PHP

我想合并一些 json 文件并在使用 foreach 函数后显示它们。

$urls = array( 'url_1','url_2', 'url_3', 'url_4', 'url_5');
$jobs = [];
foreach ($urls as $url){
$json = json_decode(get_content($url), true);
$jobs[] = $json;
}
$retour = json_encode($jobs);
foreach($retour as $job) {
 echo $job;
}

但是我的屏幕上没有任何显示。我也没有错误。

当我做 echo $retour; 时,我得到的是 [[{...},{...},{...},{...},{...},{...}]] 而不是 [{...},{...},{...},{...},{...},{...}]

如何解决这个问题?

我已经尝试了以下方法,它似乎如您所愿

<?php
 $urls = array( 'url_1','url_2');
 $jobs = [];
 foreach ($urls as $url){
   $json = json_decode(file_get_contents($url), true);
   array_push($jobs, $json);
 }

 $unique = array();
 foreach ($jobs as $piece) {
    $unique = array_merge($unique, $piece);
 }
 $retour = json_encode($unique);
 print_r($retour); //it gives merged json :: {"key1":"value1","key2":"value2","key3":"value3","key4":"value4"}
 $test[] = $retour;
 print_r($test); //to get it as array :: ([0] => {"key1":"value1","key2":"value2","key3":"value3","key4":"value4"})
?>

我创建了 url_1 和 url_2 作为 json 文件如下

{
  "key1": "value1", 
  "key2": "value2"
}

{
  "key3": "value3",
  "key4": "value4"
}