gpt4 book ai didi

php - foreach里面的foreach合并两个mysql查询结果

转载 作者:行者123 更新时间:2023-11-29 16:20:43 25 4
gpt4 key购买 nike

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

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

请帮忙吗?

最佳答案

简单地单独运行循环,而不是一个循环运行另一个循环......:

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

关于php - foreach里面的foreach合并两个mysql查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54521029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com