简体   繁体   中英

PHP: How can I split a foreach-loop into 3 parts?

I have a little problem on my website. I have a Blog and every article is in one list. Now I want to split this one list into 3 lists.

My Problem:

<ul class="row-3">
<?php $i = 1; foreach($posts as $post): ?>
    <?php if($i % 3 == 0): ?>
        <?php echo "$article" ?>              
    <?php endif; $i++; ?>
<?php endforeach ?>
</ul>

<ul class="row-2">
<?php $i = 1; foreach($posts as $post): ?>
    <?php if($i % 2 == 0): ?>
        <?php echo "$article" ?>              
    <?php endif; $i++; ?>
<?php endforeach ?>
</ul>

If I make it like this will every third loop go into the third list and every second loop into the second list. But the problem is:

Article 5 and 10 will be in both lists...

So I have to split the whole foreach-loop into 3 parts that a counter count until 3 and then if its at 3 it changes to 0 again so I can put every 1 into the first list every 2 into the second and every 3 into the third list but I have absolutely no idea how I can solve this.

I hope you guys can help me a bit and I'm sorry for my bad english..

Thanks a lot.

I'm not surer that this will work with your ordering, but array_chunk, https://secure.php.net/manual/en/function.array-chunk.php , may do what you want.

This way you don't have to deal with the sharing a common multiple.

If ordering is an issue, there is a comment on the array_chunk page which has some code that does an array_chunk_vertical. One of these two methods should get you what you need.

Something like this untested code below:

// Each group will be in it's own section array. $sections = array_chunk($posts, 2);

So the soulution to my little problem was pretty easy ^^ :

<?php
function partition( $list, $p ) {
    $listlen = count( $list );
    $partlen = floor( $listlen / $p );
    $partrem = $listlen % $p;
    $partition = array();
    $mark = 0;
    for ($px = 0; $px < $p; $px++) {
        $incr = ($px < $partrem) ? $partlen + 1 : $partlen;
        $partition[$px] = array_slice( $list, $mark, $incr );
        $mark += $incr;
    }
    return $partition;
}

$sec1 = partition($posts, 3);
$sec2 = partition($posts, 3);
$sec3 = partition($posts, 3);
?>

So I found this function on Stack Overflow wich split a array in 3 parts (or every other number you wirte instead of x: partition($array, x); ).

Then the rest was easy:

<?php foreach($sec1[0] as $post): ?>
    ...
<?php endforeach ?>

I only had to make 3 sections for each list and a foreach for every list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM