Can someone help me to solve this array issue? I am using a MySQL database, I'm trying to fetch values from two tables in two while loops. I want to merge result as I have described below. I've tried achieving this with the following code, however, this does not work for me.
$jsonObj= array();
$query="SELECT * FROM `tbl_news` ORDER BY `news_type` desc limit 50, 100";
$sql0 = mysqli_query($mysqli,$query) or die(mysqli_error($mysqli));
while($data = mysqli_fetch_assoc($sql0))
{
$nid = $data['id'];
$cquery = "select id from tbl_comments where news_id = '$nid'";
$cresult = mysqli_query($mysqli,$cquery);
$totalc = mysqli_num_rows($cresult);
$row['id'] = $data['id'];
$row['news_type'] = $data['news_type'];
$row['news_heading'] = stripslashes($data['news_heading']);
//Comments
$qry2="SELECT * FROM tbl_comments WHERE tbl_comments.`news_id`='".$nid."'";
$result2=mysqli_query($mysqli,$qry2);
$row2['totalc'] = $result2->num_rows;
if($result2->num_rows > 0)
{
while ($row_comments=mysqli_fetch_array($result2)) {
$row2['comment_id'] = $row_comments['id'];
$row2['news_id'] = $row_comments['news_id'];
$row2['user_name'] = $row_comments['user_name'];
$row2['user_email'] = $row_comments['user_email'];
$row2['comment_text'] = $row_comments['comment_text'];
$row['user_comments'][]= $row2;
}
}
else
{
$row2 = array();
}
array_push($jsonObj,$row);
}
$set['SET_News'] = $jsonObj;
header( 'Content-Type: application/json; charset=utf-8' );
echo $val= str_replace('\\/', '/', json_encode($set,JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
die();
I am expecting this result
"Set_News": [{
{
"id": "104",
"news_type": "any",
"news_heading": "Mews heade here 1",
"user_comments": [{
"totalc": 2,
"comment_id": "17",
"news_id": "104",
"user_name": "abhijeet",
"user_email": "XXX@gmail.com",
"comment_text": "nice"
},
{
"totalc": 2,
"comment_id": "18",
"news_id": "104",
"user_name": "abhijeet",
"user_email": "XXX@gmail.com",
"comment_text": "nice"
}
],
{
"id": "622",
"news_type": "any",
"news_heading": "News head here2",
},
}
}];
You can check result here... this is getting repeat inrelavent result comment list