我有$array=array("nothing","1","2","3","4","5","6","7","8","9","10");
和一段代码作为模板:
$var=<<<EOF
$array[0]
<div>
<!-- something else -->
<ul>
<li>$array[1]</li>
<li>$array[2]</li>
<li>$array[3]</li>
</ul>
<!-- something else -->
</div>
EOF;
我希望动态重复和修改此HTML代码,同时有数组元素。我的意思是这个结果:
$var=<<<EOF
$array[0]
<div>
<!-- something else -->
<ul>
<li>$array[1]</li>
<li>$array[2]</li>
<li>$array[3]</li>
</ul>
<!-- something else -->
</div>
<div>
<!-- something else -->
<ul>
<li>$array[4]</li>
<li>$array[5]</li>
<li>$array[6]</li>
</ul>
<!-- something else -->
</div>
<div>
<!-- something else -->
<ul>
<li>$array[7]</li>
<li>$array[8]</li>
<li>$array[9]</li>
</ul>
<!-- something else -->
</div>
<div>
<!-- something else -->
<ul>
<li>$array[10]</li>
</ul>
<!-- something else -->
</div>
EOF;
答案 0 :(得分:1)
<?php
$array[0];
for ($i = 0; $i <= count($array); $i + 3) {
?>
<div>
<!-- something else -->
<ul>
<li><? $array[$i + 1] ?></li>
<li><? $array[$i + 2] ?></li>
<li><? $array[$i + 3] ?></li>
</ul>
<!-- something else -->
</div>
<?php } ?>
你想要的循环不是标准的,所以只能希望它适合你。
基本上它以$i = 0
开头,并打印$i + 1
(= 1),(= 2),(= 3),下一轮$i
等于3($i + 3
),并打印$i + 1
(= 3 + 1 = 4),(= 5),(= 6),依此类推,直到数组到达终点。
答案 1 :(得分:1)
扩展@Nadav的答案并使其更好:
<?php
$array = array(0);
for ($i = 1; $i < count($array); ): ?>
<div>
<!-- something else -->
<ul>
<li><?php echo $array[$i++] ?></li> // i == 1, 4, 7, ....
<li><?php echo $array[$i++] ?></li> // i == 2, 5, 8, ....
<li><?php echo $array[$i++] ?></li> // i == 3, 6, 9, ....
</ul>
<!-- something else -->
</div>
<?php endfor; ?>
但是如果2,3不存在或者5,6不存在,那么上面的将会失败。
此代码将正常运行:
<?php
$array = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 11, 22);
for ($i = 1; $i < count($array);): ?>
<div>
<!-- something else -->
<ul>
<?php for($j = 0; $j < 3 && $i + $j < count($array); ++$j):?>
<li><?php echo $array[$j + $i] ?></li>
<?php endfor; $i += $j;?>
</ul>
<!-- something else -->
</div>
<?php endfor; ?>