php - 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 循环在帖子和评论中循环多次,然后显示两次
有什么帮助吗?
解决方案
只需单独运行你的循环,而不是一个在另一个里面......:
foreach($posts as $post) {
echo $post['postContent']."<br>";
}
foreach($comments as $comment) {
echo $comment['commentContent']."<br>";
}
推荐阅读
- javascript - 为焦点上的jquery可拖动元素添加边框
- r - 如何在 geom_density 上指定两条具有不同颜色和形状的曲线
- java - 有什么方法可以加密外部 SD 卡上的 SQLite 数据库?
- c# - 向 AD 查询 LAPS ExpirationTime 时返回 System.__ComObject
- python-3.x - Scrapyd 不会将包含 selenium 模块的蜘蛛项目部署到我的本地主机
- android - Bindable 必须在 Observable 类的成员上
- string - 如何将 chr(47) '\' 添加到字符串中?
- postgresql - 可以通过 shell 连接到 postgres 容器,但不能通过 phoenix app
- java - 在 Spring REST 应用程序中实现调解器设计模式?
- sorting - 使用文档的数组字段在 N1QL 中对文档进行排序