里面的foreach的foreach结合两个MySQL查询的结果

问题描述 投票:0回答:1

我的查询产生两个结果一样

然后,我已经尝试拉动的结果与两个阵列有两个while循环

while ($rowPost = mysqli_fetch_assoc($grabPostsQuery)) { 
  $posts[] = $rowPost;            
}
while ($rowComment = mysqli_fetch_assoc($grabCommentsQuery)) {
   $comments[] = $rowComment;
}

$grabPostsQuery = "SELECT * FROM posts ORDER BY postDate DESC";
$grabPostsQuery = mysqli_query($link, $grabPostsQuery);
$grabCommentsQuery = "SELECT * FROM comments ORDER BY commentDate DESC";
$grabCommentsQuery = mysqli_query($link, $grabCommentsQuery);

然后我由嵌套的foreach等作为它遵循

foreach($posts as $post) {
   foreach($comments as $comment) {
       echo $post['postContent']."<br>";
       echo $comment['commentContent']."<br>";
   }
}

我可以访问文章和评论,唯一的问题是,foreach循环通过文章和评论循环多次,然后显示他们两次

任何帮助吗?

php mysql foreach
1个回答
0
投票

只需单独运行的循环,而不是一个在另一个内...:

foreach($posts as $post) {
  echo $post['postContent']."<br>";
}
foreach($comments as $comment) {
  echo $comment['commentContent']."<br>";
}
© www.soinside.com 2019 - 2024. All rights reserved.