php - PHP 将 2 个 Json 合并为 1 个
问题描述
我有 2 个要解析的 JSON 文件,并合并到一个对象中并作为单个 JSON 输出。但我不知道该怎么做并得到正确的结果,每次我尝试总是得到一个这样的结果:
[
{
"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"
}
]
解决方案
要对对象执行此操作(如您当前使用的那样),您可以使用第一个数组的索引从第二个数组中获取数据。然后使用来自两个对象的组件一次性构建输出并将它们添加到您的输出中......
$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);
推荐阅读
- azure-devops - 如何在 azure-pipelines.yml 文件中为 docker 图像添加自定义构建标签?
- javascript - React-Native:下载和运行外部 Javascript 文件
- makefile - 需要重新制作的打印目标
- javascript - 使用 Vue 鼠标悬停事件在两个元素上设置样式非常滞后。有一个更好的方法吗?
- python - 将使用 ui 文件加载的 .py 转换为 exe 时出错
- c# - 裁剪具有多个 X 和 Y 点的图像 c#
- rest - 使用 REST API 更新 Hybris 数据中的关系,未保存嵌套关系
- python - 如何使用 python 计算 slearn.roc_auc_score?
- c++ - 为什么当 i++ 被定义为 for 循环中的增量时没有立即增量,而它反映在 if 语句的情况下?
- kubernetes - 在入口控制器后面的 Kubernetes 集群中运行 Graylog