首页 > 解决方案 > foreach里面foreach合并两个mysql查询结果

问题描述

我的查询生成两个结果,例如

然后我尝试用两个带有两个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 循环在帖子和评论中循环多次,然后显示两次

有什么帮助吗?

标签: phpmysqlforeach

解决方案


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

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

推荐阅读