Skip to content
Advertisement

How to align comments under its posts via PHP

I have two json records which I can successfully display its records separately.

Here is my issue. I want to append and display the comments of the second record based on the postid of the first record.

That is, I want to place all the comments under its post based on the postid.

<?php

// first record
$output ='
{"results":[
{"postid":101, "post":"my first post"},
{"postid":102, "post":"my second post"},
{"postid":103, "post":"my third post"}]
}
';


// second record
$output2 ='
{"results":[
{"postid":101,"comment":"my first comment"},
{"postid":102, "comment":"my second comment"},
{"postid":103,"comment":"my third comment"}
]
}
';


$json = json_decode($output, true);
foreach($json["results"] as $res){

            
echo $id = $res['postid'];
echo "<br><br>";

echo $post = $res['post'];
echo "<br><br>";
  
}




$json2 = json_decode($output2, true);
foreach($json2["results"] as $res1){

            
echo $id = $res1['postid'];
echo "<br><br>";

echo $comment = $res1['comment'];
echo "<br><br>";

  
}


?>

Advertisement

Answer

You need to add second json_decode, and inside loop take comments from that.

<?php

// first record
$output ='
{"results":[
{"postid":101, "post":"my first post"},
{"postid":102, "post":"my second post"},
{"postid":103, "post":"my third post"}]
}
';


// second record
$output2 ='
{"results":[
{"postid":101,"comment":"my first comment"},
{"postid":102, "comment":"my second comment"},
{"postid":103,"comment":"my third comment"}
]
}
';


$json = json_decode($output, true);
$json2 = json_decode($output2, true);

foreach($json["results"] as $key => $res){


echo $id = $res['postid'];
echo "<br><br>";

echo $post = $res['post'];
echo "<br><br>";
echo $json2['results'][$key]['comment'];
echo "<br><br>";

}

Output

101

my first post

my first comment

102

my second post

my second comment

103

my third post

my third comment
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement