从多个 URL 获取 JSON 数据,然后在新 URL 中再次推送它

  • 本文关键字:URL 然后 获取 JSON 数据 php
  • 更新时间 :
  • 英文 :


我有 2 个 api 一个用于帖子和评论,这是帖子的形式:

[
{
Iduser: 1,
id: 1,
subject: "subject",
description: "description"
},
{
Iduser: 1,
id: 2,
subject: "subject",
description: "description"
},
{
Iduser: 1,
id: 3,
subject: "subject",
description: "description"
}]

这是注释 API 的形式:

[
{
Idpost: 1,
id: 1,
title: "title",
description: "description"
},
{
Idpost: 1,
id: 2,
title: "title",
description: "description"
},
{
Idpost: 1,
id: 3,
title: "title",
description: "description"
}]

所以我想获取用户 ID 并推送新的 json api 在每个用户 ID 的一个 json 对象中包含帖子及其评论

这是我开始的代码:

<?php 
$json1 = file_get_contents('https://');
$json2 = file_get_contents('https://');
$data1 = json_decode($json1,true);
$data2 = json_decode($json2,true);
$userId = "1";
$user = "";
foreach ($data1 as $key => $value) {
if($value['userId'] == $userId)
{
$user = $value['userId'];
echo $user
}
}
?>

当我回显$user时,我得到了正确数量的idUser,它们的值为1 但是当我尝试将其推送为数组以再次对其进行编码时,如下所示:

foreach ($data1 as $key => $value) {
if($value['userId'] == $userId)
{
$user = $value['userId'];
}
$channels_item[] = array(
"id" => $user,
);
}
echo json_encode($channels_item);

我刚刚在 json 中得到了一百多个对象,其中 id=1

如何解决这个问题

您必须在条件中向数组添加一个 ID,否则 Foreach 将添加保留在变量中的旧数据。

foreach ($data1 as $key => $value) {
if($value['userId'] == $userId)
{
$user = $value['userId'];
$channels_item[] = ["id" => $user];
}
}
echo json_encode($channels_item);

这应该会有所帮助

<?php
error_reporting(0);
$json1 = file_get_contents('https://jsonplaceholder.typicode.com/posts');
$json2 = file_get_contents('https://jsonplaceholder.typicode.com/comments');
$data1 = json_decode($json1,true);
$data2 = json_decode($json2,true);
print_r($data1);
foreach($data1 as $val){
foreach($data2 as $value){
if(empty($val['Iduser'])){break;}
if($val['Iduser'] === $value['Idpost']){
$result[] = ["Idpost" => $value['Idpost'], "Iduser" => $val["Iduser"], "title" => $value["title"], "description" => $value["description"], "subject" => $val["subject"], "descriptionjson1" => $val["description"]];
}
}
}
print_r($result);
?>

最新更新