继续这个场景,我有7个项目的数组,我想在每第四次迭代中将它们分开..就像这样
$counter2 = 0;
$counter3 = 0;
$counter4 = 0;
$sample_array = array('Aso','Pusa','Daga','Kuting','Tuta','Bubwit','Boom');
foreach($sample_array as $sample_array_value)
{
if(++$counter4 % 4 == 0)
{
echo $sample_array_value;
echo "</div>";
}
elseif(++$counter3 % 3 == 0)
{
echo $sample_array_value;
}
elseif(++$counter2 % 2 == 0)
{
echo $sample_array_value;
}
else
{
echo "<div>";
echo $sample_array_value;
}
}
输出将是div AsoPusaDagaKuting / div div TutaBubwitBoom
问题是它在迭代结束时不计数4它不会给分隔符结束..
我需要输出div AsoPusaDagaKuting / div div TutaBubwitBoom / div
提前致谢...
答案 0 :(得分:3)
你可以用array_chunk拆分它,用array_map压缩4的新子数组,然后用implode回显它。
$sample_array = array('Aso','Pusa','Daga','Kuting','Tuta','Bubwit','Boom');
echo "<div>", implode("</div><div>", array_map("implode", array_chunk($sample_array, 4))), "</div>";
结果:
<div>AsoPusaDagaKuting</div><div>TutaBubwitBoom</div>
答案 1 :(得分:2)
您正在每个条件下打印值,那么为什么不在任何条件之外使用echo
?您还想关闭并打开第四个元素的div
标记,然后只有一个计数器可以完成这个操作。只有这会起作用 -
$sample_array = array('Aso','Pusa','Daga','Kuting','Tuta','Bubwit','Boom');
$i = 0;
echo "<div>";
foreach($sample_array as $sample_array_value)
{
if($i > 0 && $i % 4 == 0)
{
echo "</div><div>";
}
echo $sample_array_value;
$i++;
}
echo "</div>";
<强>输出强>
<div>AsoPusaDagaKuting</div><div>TutaBubwitBoom</div>
答案 2 :(得分:2)
试试这个:
$i = 0;
foreach($sample_array as $sample_array_value)
{
if(++$counter4 % 4 == 0)
{
echo $sample_array_value;
echo "</div>";
}
elseif(++$counter3 % 3 == 0 || ++$counter2 % 2 == 0)
{
echo $sample_array_value;
}
else
{
echo "<div>";
echo $sample_array_value;
}
$i++;
}
if ($i % 4 != 0) {
echo "</div>";
}