【发布时间】:2013-05-26 17:38:25
【问题描述】:
我想使用 for each 循环显示我的 MYSQL 数据库中两个表的结果。目前我已将两个表分成两个单独的循环,如下所示:
<?php
$i = 0;
foreach (array_reverse ($articles) as $article){?>
<div class="greyvertical midtopmargin item leftpadding rightpadding">
<a href="article.php?id=<?php echo $article['article_id']; ?>"><img src="../lifestyle/photos/articles/<?php echo $article['photo_folder']; ?>/<?php echo $article['photo_1']; ?>" alt="item">
<h5 class="whitetext text2 extrabold smalltoppadding leftpadding"><?php echo $article['article_title']; ?></h5></a>
<p class="meta whitetext leftpadding smalltoppadding">
<?php echo $article['article_summary']; ?></p>
<a href="article.php?id=<?php echo $article['article_id']; ?>" class="whitetext text2 mediumfont leftpadding midbottommargin">READ ME</a>
</div>
<?php if (++$i == 5) break;
} ?>
<?php
$i = 0;
foreach (array_reverse ($posts) as $post){?>
<div class="greyvertical midtopmargin item leftpadding rightpadding">
<a href="post.php?id=<?php echo $post['post_id']; ?>"><img src="../lifestyle/photos/blog/<?php echo $post['photo_folder']; ?>/<?php echo $post['photo_bg']; ?>" alt="item">
<h5 class="whitetext extrabold text2 leftpadding smalltoppadding"><?php echo $post['post_title']; ?></h5></a>
<p class="meta leftpadding whitetext smalltoppadding">
<?php echo $post['post_summary']; ?></p>
<a href="post.php?id=<?php echo $post['post_id']; ?>" class="whitetext text2 mediumfont leftpadding midbottommargin">READ ME</a>
</div>
<?php if (++$i == 5) break;
} ?>
正如您所看到的,它们几乎相同,但略有不同,但我完全不知道如何将两者结合起来,而不像现在这样将它们分开。谁能用外行的话让我知道如何将两个循环合并为一个?即我想组合文章和帖子表,以便它们将显示为一个而不是单独显示。在此先感谢各位。
【问题讨论】:
-
$article和$posts中有什么内容? -
在您的开发过程中,您似乎偏离了恕我直言的模式。要解决您的问题 - 您应该简单地设置一个条件来检查是否存在仅出现在 $article 或 $posts 中的值,然后在 foreach 中做出相应的反应。
-
$article = 新文章; $post = 新邮政; $articles = $article->fetch_all(); $posts = $post->fetch_all();
-
您似乎可以从头开始控制每个变量,为什么不简单地将两个数组推在一起并检查数组键值,然后使用三元变量赋值来处理您需要的细微差别切换?
-
例如 $article= new Article;新邮政; ?
标签: php mysql foreach content-management-system