PHP将2个Json合并为1个
我有两个JSON文件要解析,合并成一个对象并作为单个JSON输出。 但我不知道如何做才能得到正确的结果,每次尝试都会得到这样一个结果:PHP将2个Json合并为1个,php,arrays,json,Php,Arrays,Json,我有两个JSON文件要解析,合并成一个对象并作为单个JSON输出。 但我不知道如何做才能得到正确的结果,每次尝试都会得到这样一个结果: [ { "Title": "Some title for your blog", "url": "\/post.php?id=1", "image": "https:\/\/example.com\/images\/small\/1.jpg" } ] 我需要的是将所有2个json数据调用为1个js
[
{
"Title": "Some title for your blog",
"url": "\/post.php?id=1",
"image": "https:\/\/example.com\/images\/small\/1.jpg"
}
]
我需要的是将所有2个json数据调用为1个json,如下所示:
[
{
"Title": "second title for your blog",
"url": "\/post.php?id=2",
"image": "https:\/\/example.com\/images\/small\/2.jpg"
}
{
"Title": "second title for your blog",
"url": "\/post.php?id=2",
"image": "https:\/\/example.com\/images\/small\/2.jpg"
}
{
"Title": "third title for your blog",
"url": "\/post.php?id=3",
"image": "https:\/\/example.com\/images\/small\/3.jpg"
}
and so on... till the end of loop
]
这是我的密码:
$requestUrl="http://example.com/json1.php";
$requestUrl1="http://example.com/json2.php";
$data=file_get_contents($requestUrl);
$data1=file_get_contents($requestUrl1);
$array1 = json_decode($data);
$array2 = json_decode($data1);
$wholedata= [];
$i=0;
foreach ($array1 as $array1) {
$item['Title'] = $array1->title;
$item['url'] = $array1->url;
}
foreach ($array2 as $array2) {
$item['image'] = $array2->image;
}
$wholedata[] = $item;
$i++;
$json = json_encode($wholedata, JSON_PRETTY_PRINT);
header('Access-Control-Allow-Origin: *');
header('Content-type: Application/JSON');
echo $json;
以下是json数据:
Json 1
[
{
"title": "first title for your blog",
"url": "/post.php?id=1"
},
{
"title": "Second title for your blog",
"url": "/post.php?id=2"
},
{
"title": "Third title for your blog",
"url": "/post.php?id=3"
},
{
"title": "Fourth title for your blog",
"url": "/post.php?id=4"
},
{
"title": "Fifth title for your blog",
"url": "/post.php?id=5"
}
]
Json 2:
[
{
"image": "https://example.com/images/small/1.jpg"
},
{
"image": "https://example.com/images/small/2.jpg"
},
{
"image": "https://example.com/images/small/3.jpg"
},
{
"image": "https://example.com/images/small/4.jpg"
},
{
"image": "https://example.com/images/small/5.jpg"
}
]
尝试在数组中对json进行去编码,然后合并它们。查看PHP官方文档 -合并两个阵列 -将json转换为数组要对对象执行此操作(正如您当前使用的),可以使用第一个数组的索引从第二个数组获取数据。然后使用两个对象的组件一次性生成输出,并将它们添加到输出中
$array1 = json_decode($data);
$array2 = json_decode($data1);
$wholedata= [];
foreach ($array1 as $key => $itemData) {
$wholedata[] = ['Title' => $itemData->title,
'url' => $itemData->url,
'image' => $array2[$key]->image];
}
$json = json_encode($wholedata, JSON_PRETTY_PRINT);
尝试在数组中对json进行去编码,然后将它们合并并不是一个特别有用的答案(IMHO)