简体   繁体   中英

Merge 2 Json file in PHP

i want to merge some json file and display them after using a foreach function.

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

But nothing appear on my screen. And i have no error too.

When i do echo $retour; i have something like [[{...},{...},{...},{...},{...},{...}]] instead of [{...},{...},{...},{...},{...},{...}] .

How to solve this ?

I have tried the following and it seems to work as you want

<?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"})
?>

I have created url_1 and url_2 as json file as follow

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

and

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM