从多个网址获取json数据,然后将其再次推送到新网址中

时间:2018-10-23 20:10:45

标签: 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并在每个用户ID的一个json对象中推送新的json api包含帖子及其评论

这是我开始的代码:

<?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);

我刚在id = 1的json中获得了一百多个对象

如何解决这个问题

1 个答案:

答案 0 :(得分:1)

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

List<File> files = new ArrayList<>() // File objects added earlier
String paths = null;
    for (File file : files){
        if (file.isFile()) {
            paths += file.getName() + "\n"; 
        }
    }

    taTemp.setText(paths);

这应该有帮助

 foreach ($data1 as $key => $value) {
       if($value['userId'] == $userId)
       {
           $user = $value['userId'];

           $channels_item[] = ["id" => $user];
       }

     }

    echo json_encode($channels_item);