Wrapping 3 objects or less inside a while / foreach in PHP

…衆ロ難τιáo~ 提交于 2019-12-10 17:55:11

问题


Simple question. I have an array of 21 elements, and show every three of them inside a <div> block. The code is something like this:

<?php
$faces= array(
  1 => 'happy',
  2 => 'sad',
  (sic)
  21 => 'angry'
);

$i = 1;
foreach ($faces as $face) {
  echo $face;
  $i++;
}

?>

The problem lies when this array doesn't have 21 elements, sometimes it gets 24, an other times 17. How I wrap every three of them, and wrap alone the rest? I came up with using switch and case, but that works only when there are 21 elements only. I think I could count them beforehand and put a closing in the last one (even if it is a group of one element).


回答1:


You already have most of it here. All you're missing is something to test if you're ready to wrap. So before you increment $i, try:

$i = 1;

foreach ($faces as $face)
{
    echo $face;

    if ($i % 3 == 0)
    {
        echo "<br />"; // or some other wrapping thing
    }
    $i++;
}

This will ensure you're wrapping every 3 faces, leaving any remainder in the final unit.




回答2:


print '<div>';
$i = 1;
foreach ($faces as $face) {
  if ($i % 3 == 0) print '</div><div>';
  echo $face;
  $i++;
}
print '</div>';



回答3:


I would use array_chunk. You can split the array into a multi-dimensional array in groups of three. If the number of elements is not a multiple of three, the last element will contain all of the remaining child elements, however many they may be.



来源:https://stackoverflow.com/questions/11268901/wrapping-3-objects-or-less-inside-a-while-foreach-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!