-1

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

dimitar.bogdanov
  • 387
  • 2
  • 10
  • Just change `$row2['wid']` to `$row['wid']` etc. and data, data2 will end up in the same array? Or am I missing something here? – Markus AO Jun 19 '20 at 16:46
  • Why `$row2['greet'] = $row2;` do this? You may need to rethink your data structure a bit. – Markus AO Jun 19 '20 at 16:50
  • Thanks, @MarkusAO to respond, I have just added new key greet, and under this key, I want to fetch $data2 in while loop, nothing gets result by using $row2['wid'] to $row['wid'] – Abhijeet Shinde Jun 19 '20 at 16:58
  • I updated my answer. – Samuel Jun 19 '20 at 18:05
  • Thanks, @Samuel I have once again updated the question with actual image result, same problem here, I hope you understand this time. comments results are repeating. – Abhijeet Shinde Jun 19 '20 at 19:36
  • It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Jun 19 '20 at 22:08

1 Answers1

0

UPDATED ANSWER:

I think I understand what you want to do now. you are trying to create a sub-array, "greet", in $row containing all of the wallpapers associated with that news article. To get results you want you don't have to merge the row2 and row arrays, you just make row2 a part of row1

//...
$row2= array();
while($data2 = mysqli_fetch_array($result2))
{
    array_push($row2,$data2);
} 

if (count($row2) > 0) {
    $row["greet"] = $row2;
}

//...

This code should generate the json you have posted.

merging the arrays would create something like this instead:

"id": "30",
"news_type": "image",
"news_heading": "News title",
"news_weburl": "#",
"total_share": "0",
"cat_id": "112",
"category_name": "tech",
"wid": "11",
"wall_title": "tech image wallpaper1",
"wall_image": "image1.jpg",

and could only be done with one image

If you were wanting it to look like above if there was only one image you could change the code like this

if (count($images) == 1) {
    $row["wid"] = $row2[0]["wid"];
    $row["wall_title"] = $row2[0]["wall_title"];
    $row["wall_image"] = $row2[0]["wall_image"];
} elseif (count($row2) > 1) {
    $row["greet"] = $row2;
}

//...

Samuel
  • 1,073
  • 11
  • 22
  • Thanks for response @Samuels, I need to merge $data and $data2 in a single array, I have try to clarify in question and code. – Abhijeet Shinde Jun 19 '20 at 17:29
  • Hi @Samuels, One more example, it's working fine but results are repeating (comments are repeating) – Abhijeet Shinde Jun 19 '20 at 19:18
  • I suspect that is because you created the `$row2` array outside of the main while loop and are not clearing it with every loop. In the top example I gave I have `$row2= array()` right before the inner while loop. Try adding that. – Samuel Jun 19 '20 at 19:46
  • results are repeating (comments are repeating) – Abhijeet Shinde Jun 19 '20 at 20:13