M-Farah
M-Farah

Reputation: 33

two nested foreach

I have 2 tables in database first one is $slide_images and second is $why_us and I am using owl carousel for images.

I need each image take one row of $why_us that's mean the first 3 images will have a text from $why_us table. I tried many ways to do that but it's not given me what I want and I can't edit tables to do that and the id column is not nested to join them with SQL. Can i solve them with nested foreach?

<div class="home_area">
            <!-- start Carousel -->
        <div class="owl-carousel block_1">
                <?php
                if(is_array($slide_image)){
                foreach($slide_image as $src){
            ?>  
            <div class="overlay-text">
                <div class="carousel_item" style="background-image:url('<?php echo base_url(); echo $src->url; ?>');"></div>
                    <div class="text-layer">

                        <!--============ start we us ================ -->
                            <?php if($why_us != ''){ ?>
                                <div class="we">
                                    <div class="container">
                                        <div class="row">
                                                <?php foreach($why_us as $we){ ?>
                                                    <div class="box">
                                                        <h6><?php echo $we->name; ?></h6>
                                                        <div class="text"><?php echo $we->desc; ?></div>
                                                    </div>
                                            <?php }?>
                                        </div>
                                    </div>
                                </div>
                            <?php } ?>
                        <!--============= end we us ========== -->

                    </div>
            </div>
            <?php } }?>
        </div>
        <!-- end Carousel -->
</div>

I hope I described my question well.

Upvotes: 1

Views: 142

Answers (1)

Barmar
Barmar

Reputation: 781088

You should not use nested loops. That creates a cross product between the arrays.

Instead, you should just have one loop that uses the corresponding elements of both arrays. Since one of the arrays is smaller, you should check that the index exists.

foreach ($slide_image as $index => $src) {
    // code that uses `$src` here
    if (isset($why_us[$index])) {
        $we = $why_us[$index];
        // code that uses $we here
    }
}

Upvotes: 3

Related Questions