1

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

如您所见,它们几乎相同,但略有不同,但我完全坚持如何将两者结合起来,而不像现在这样分开。谁能用外行的话让我知道如何将两个循环合并为一个?即我想组合文章和帖子表,以便它们将显示为一个而不是单独显示。提前谢谢你们。

4

1 回答 1

0

对您的问题所做的评论是有道理的,您应该将它们考虑在内,但是有一种方法可以使用 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
于 2013-05-26T17:55:18.227 回答