【问题标题】:render different html based on even/odd in foreach (php)根据 foreach (php) 中的偶数/奇数呈现不同的 html
【发布时间】:2018-08-17 12:48:05
【问题描述】:

您好,我想根据foreach 中的奇数或偶数帖子呈现不同的 html。我现在有这个代码:

<?=fuel_edit('create', 'Create Post', 'blog/posts')?>
<?php if (!empty($posts)) : ?>
    <?php foreach($posts as $post) : ?>
        <div class="cell small-12 large-6"></div>
        <div class="cell small-12 large-6">
            <div class="post">
                <?=fuel_edit($post)?>

                <?=blog_block('post_unpublished', array('post' => $post))?>

                <h2><a href="<?=$post->url?>"><?=$post->title?></a></h2>

                <div class="post_date">
                    <?=day($post->publish_date, 'd')?>.<?=month($post->publish_date, 'm')?>
                    <!--by <strong><span class="post_author_name"></*?=$post->author_name?></span></strong-->
                </div>

                <div class="post_content">
                    <?php if ($post->has_thumbnail_image()) : ?>
                        <img src="<?=$post->get_thumbnail_image_path()?>" alt="">
                    <?php endif; ?>
                </div>
                <div class="post_meta">
                    <?=$post->tags_linked ?>
                </div>
            </div>
            <div class="clear"></div>
        </div>
    <?php endforeach; ?>

<?php else: ?>
<div class="no_posts">
    <p>There are no posts available.</p>
</div>
<?php endif; ?>

我想在奇怪的时候渲染第一个空的&lt;div class="cell small-12 large-6"&gt;&lt;/div&gt;,甚至这个 div 什么时候在第二个 &lt;div class="cell small-12 large-6"&gt;&lt;/div&gt; 之后渲染

请帮帮我,我想不通。

【问题讨论】:

    标签: php html foreach split


    【解决方案1】:

    如果您想知道帖子列表中的帖子是偶数还是奇数,您可以在循环浏览帖子时跟踪循环索引。

    在以下示例中,每次执行循环时都会增加$index。通过检查 $index 是否可以被 2 整除,您知道它是偶数并呈现所需的内容:

    <?php $index = 0; foreach($posts as $post) : ?>
      <?php if($index % 2 == 0) { $?>
        <!-- HTML for even post here. -->
      <?php } else { ?>
        <!-- HTML for odd post here. -->
      <?php 
        } 
        $index = $index + 1;
      ?> 
    <?php endforeach; ?>
    

    【讨论】:

      猜你喜欢
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      • 2017-12-11
      相关资源
      最近更新 更多