John Davidson

How to align comments under its posts via PHP

0 comments
Message:


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>";


}


?>


My Answer:
To align the comments under their respective posts based on the postid, you can modify your code as follows:

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 $res){
echo $id = $res['postid'];
echo "

";
echo $post = $res['post'];
echo "

";

// Loop through the comments and display them under the respective post
foreach($json2["results"] as $res1){
if($res1['postid'] == $id){
echo $comment = $res1['comment'];
echo "

";
}
}
}

?>


This code will display the posts from the first record and then loop through the comments from the second record to display them under their respective posts based on the postid.

Rate this post

4 of 5 based on 4814 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us