Reputation: 865
I have 2 api one for posts and comments this is the form of posts:
[
{
Iduser: 1,
id: 1,
subject: "subject",
description: "description"
},
{
Iduser: 1,
id: 2,
subject: "subject",
description: "description"
},
{
Iduser: 1,
id: 3,
subject: "subject",
description: "description"
}]
and this is the form of comments 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"
}]
so I want to get the user id and push new json api contain posts and their comments in one json object for each user id
this is the code that I start with:
<?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
}
}
?>
when I echo the $user I get the right number of idUser which their values are 1 but when I tried to push it as array to encode it again like this:
foreach ($data1 as $key => $value) {
if($value['userId'] == $userId)
{
$user = $value['userId'];
}
$channels_item[] = array(
"id" => $user,
);
}
echo json_encode($channels_item);
I just got more than hundred objects in the json where id=1
how solve this question
Upvotes: 0
Views: 302
Reputation: 83
You must add an ID to the array in the condition, otherwise Foreach will add old data that remained in the variable.
foreach ($data1 as $key => $value) {
if($value['userId'] == $userId)
{
$user = $value['userId'];
$channels_item[] = ["id" => $user];
}
}
echo json_encode($channels_item);
This should help
<?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);
?>
Upvotes: 1