How can i get two items in a foreach loop in PHP? [duplicate]

情到浓时终转凉″ 提交于 2021-02-05 08:08:55

问题


I have a testimonial carousel. The carousel loop through two item each time. Now i want to get two item each time in a foreach loop. How can i get it?

code:

<?php foreach ($kiyra_section_meta['testimonials-group'] as $single_testimonial):        ?>
                    <div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="single-review">
                                    <div class="media">
  <div class="media-body"> 
    <h3 class="mt-0"><?php echo esc_html($single_testimonial['client-name']);   ?></h3>
    <h5><?php echo esc_html($single_testimonial['client-position']);   ?></h5>
    <i class="fas fa-quote-right fa-5x"></i>
  </div>
                                    </div>
                                    <?php echo esc_html($single_testimonial['client-testimonial']);   ?>
                                </div><!--/.single-review-->
                            </div>

                        </div>
                    </div>

             <?php endforeach;    ?>

回答1:


You can use array_chunk to split array to group 2 item, then use foreach again

foreach (array_chunk($input_array, 2) as $group) {
    // Start Group
    foreach ($group as $item) {
        // Item
    }
    // End group
}

Update with HTML

<div class="owl-carousel">
    <?php foreach (array_chunk($input_array, 2) as $group) : ?>
        <div class="owl-item">
            <?php foreach ($group as $item) : ?>
                <div class="item">
                    <!-- Code of item -->
                </div>
            <?php endforeach; ?>
        </div>
    <?php endforeach; ?>
</div>


来源:https://stackoverflow.com/questions/55547449/how-can-i-get-two-items-in-a-foreach-loop-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!