php - 如何在 php 中为每个循环调用多个表

标签 php mysql foreach content-management-system

我想使用 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;
            } ?>

如您所见,它们几乎完全相同,但略有不同,但我完全坚持如何将两者结合起来,而不是像现在这样将它们分开。谁能用通俗易懂的方式告诉我如何将两个循环合二为一?即我想合并 articles 和 posts 表,以便它们将显示为一个而不是单独显示。提前谢谢大家。

最佳答案

对你的问题所做的评论是有道理的,你应该考虑到它们,但是有一种方法可以使用 PHP 的 MultipleIterator 一次迭代两个数组。 .这是一个非常简化的示例,说明它如何为您工作:-

$articles = array('article 1','article 2','article 3');
$posts = array('post 1', 'post 2', 'post 3');

$iterator1 = new ArrayIterator($articles);
$iterator2 = new ArrayIterator($posts);

$multiIterator = new MultipleIterator();
$multiIterator->attachIterator($iterator1);
$multiIterator->attachIterator($iterator2);

foreach($multiIterator as $combinedArray){
    echo $combinedArray[0] . "<br/>\n";
    echo $combinedArray[1] . "<br/>\n";
}

输出:-

article 1
post 1
article 2
post 2
article 3
post 3

关于php - 如何在 php 中为每个循环调用多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16761937/

相关文章:

mysql - 更改datadir后无法重启mysql

c++ - 将基于 C++11 范围的 for 循环与右值 range-init 一起使用是否安全?

javascript - 迭代值时,为什么当值是数字时 typeof(value) 返回 "string"? JavaScript

php - 如何使用多个表来创建用户配置文件?

php - PHP levenshtein() 函数有问题吗?

php - 未设置mysql最小限制

php - preg_match() 期望参数 2 是字符串,数组给定错误

php - $file->move() 函数未显示新文件夹中移动的文件?

mysql在一列中计算某些列的值

php - 同一id只显示一行