user1251698
user1251698

Reputation: 2143

Grouping loop items in php

I am trying to group each 5 loop items inside a <li></li> and then further group the each li item into two groups, so that first item of each li is in one group, while other 4 are in other group.

With the following code, I can wrap each 5 items of a loop in a li, but I am not able to group each li items into 2 groups. Since there are more than 10 items in the loop, thats why I can not hard code the values of $i to print the div.

$i = 1;
while ($i < 10){
    echo ($i % 5 === 0) ? "<li>" : null;
        $i++;
        echo item $i;
    echo ($i % 5 === 0) ? "</li>" : null;   
}
echo ($i % 5 !== 0) ? "</li>" : null;

This is the desired output:

<li>
    <div class="left">
        Item 1
    </div>
    <div class="right">
        Item 2
        Item 3
        Item 4
        Item 5
    </div>
</li>

<li>
    <div class="left">
        Item 6
    </div>
    <div class="right">
        Item 7
        Item 8
        Item 9
        Item 10
    </div>
</li>

Demo: http://codepad.org/OztLPai8

Upvotes: 0

Views: 1947

Answers (2)

Highmastdon
Highmastdon

Reputation: 7520

Working example: http://codepad.org/uHYHl6MD

<?php
// Initial group size
$groupSize = 5;
$total = 22;

// To keep track of the group
$groupCounter = $groupSize;

$isFirst = true;
$i = 1;

while($i < $total){
    echo "<li>\n";
    // Left div
    if($isFirst){
        echo "\t<div class='left'>\n";
        echo "\tItem $i\n";
        $isFirst = false;
        $i++;
        echo "\t</div>\n";
    }

    // Right div
    echo "\t<div class='right'>\n";
    while($i <= $groupCounter && $i <= $total){
        echo "\tItem $i\n";
        $i++;
    }
    echo "\t</div>\n";

    // Get to the next group
    $groupCounter += $groupSize;

    // Start with the first, first.
    $isFirst = true;

    echo "</li>\n";
}
?>

Upvotes: 1

Lauris
Lauris

Reputation: 1115

$items = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

$lis = array_chunk($items, 5);

foreach($lis as $li)
{
    echo '<li>';

    echo '<div class="left">' . $li[0] . '</div>';

    echo '<div class="right">';

    foreach($li as $key => $value)
    {
        // Skip first item
        if($key == 0)
        {
            continue;
        }

        echo $value . '<br />';
    }

    echo '</div>';

    echo '</li>';
}

Upvotes: 2

Related Questions