Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Split column when item = 4

I have an array and now I'm putting this array into for loop to show each item in this array, but I want set item limit (4 item each column), here is my code.

<?php 
    $area = $custom_area_settings; //is an array with 5 element
    for($i=0;$i<=count($area->custom_area_list) - 1; $i++):
        if($area->custom_area_list[$i]->top_show):
            echo '<div class="sub-column column'.$i.'">';
            echo '<p class="line"> ' . $area->custom_area_list[$i]->header . '</p>';
            echo '</div>';
        endif;
    endfor;
?>

On this code, div column$i had created each time loop ran but I just want this div create when loop run 4 times, after 4 times this div will create again, after 8 times this div will create again and continue...

Here is the result I want.

Column 1           Column 2
---------------    ---------------
item 1             item 5
item 2             item 6
item 3             item 7
item 4             item 8

Here is the result I'm getting now

Column 1
---------------------
item 1
Column 2
---------------------
item 2
.....

Please help.

like image 764
Johnny Nguyen Avatar asked Jul 28 '26 19:07

Johnny Nguyen


2 Answers

Updated:

$html = $i%4 === 0 ? '<div class="sub-column column'
                     . $i . '">' 
                     . '{1}' . '</div>' : '{1}';

echo strtr($html,array('{1}' => '<p class="line"> '
                              . $area->custom_area_list[$i]->header
                              . '</p>'
          ));

% divides $i by 4 and returns the remainder which must be equal to 0 in this case

like image 65
Let me see Avatar answered Jul 30 '26 08:07

Let me see


<?php
    $area = $custom_area_settings; //is an array with 5 element
    $i=0;
    echo '<div class="sub-column column'.$i.'">';
    for($i=0;$i<=count($area->custom_area_list) - 1; $i++):
        if($area->custom_area_list[$i]->top_show):
            if($i%4 === 0):
                echo '</div>';
                echo '<div class="sub-column column'.$i.'">';
            endif;
            echo '<p class="line"> ' . $area->custom_area_list[$i]->header . '</p>';
        endif;
    endfor;
    echo '</div>';
?>
like image 28
Prakash Avatar answered Jul 30 '26 10:07

Prakash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!