aqeelramay
aqeelramay

Reputation: 79

how to display two results per loop in php foreach

I have a portfolio table where there are number of rows, at the front end side of my website, I have li in which there are div, now i want to display two div in per li like in first li there are portfolio item 1 and portfolio item 2 and next li there are portfolio item 3 and portfolio item 4

following is my code

<ul class="slides">
                <?php for($i = 1; $i <= round(count($projlists)/2); $i++) { ?>
                <li>
                <?php foreach($projlists as $projlist) { ?>
                  <div class="span3"> <a class="thumbnail" href="#"> <img alt="260x180" data-src="holder.js/260x180" style="width: 260px; height: 180px;" src="<?=base_url()?>uploads/portfolio/full/<?=$projlist->portfolio_image?>"> </a> </div>
                  <?php } ?>
                </li>
                <?php  } ?>
              </ul>

following is my model

function projectlist()
{
    $query = $this->db->query("SELECT * FROM portfolio WHERE status = 1");
    if($query->num_rows() > 0) 
    {
        foreach($query->result() as $row) 
        {
            $data[] = $row;
        }
    return $data;
    }   
}

Note: i am using codeigniter

Upvotes: 2

Views: 1332

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

To show two divs in one li within loop you can do so,define a flag variable and increment it for each iteration of loop and check if the modulus of flag with 2 is zero i.e $index % 2 == 0 then close li and open li

<ul class="slides">
    <li>
        <?php
        $index = 0;
        foreach ($projlists as $projlist) {
            ?>
            <div class="span3">
                <a class="thumbnail" href="#">
                    <img alt="260x180" data-src="holder.js/260x180" style="width: 260px; height: 180px;"
                         src="<?= base_url() ?>uploads/portfolio/full/<?= $projlist->portfolio_image ?>">
                </a></div>
            <?php $index++;
            if ($index % 2 == 0 && $index !=count($projlists)) {
                echo '</li><li>';
            }
        } ?>
    </li>
</ul>

Upvotes: 1

Related Questions