我想以一种方式回显数组的值,即前4个将在一个节中回显,其余的(可以是5个或更多)将在不同的节中回隐。例如:
<?php $items = $kStore->getItems(); ?>
<div id="section1">
<?php foreach($items as $item) {
if($count <= 4){
?>
<h1><?php echo $item->getId(); ?></h1>
<?php } }?>
</div>
<div id="section2">
<?php foreach($items as $item) {
if($count > 4){
?>
<h1><?php echo $item->getId(); ?></h1>
<?php } } ?>
</div>
我想它一定是"那样"的,但不知道如何计数。另外,我不想两次通过阵列,我觉得这不是最快的方法。有什么想法吗?谢谢
您可以使用array_slice来偏移开始并限制您迭代的数组部分的长度:
<div id="section1">
<?php foreach(array_slice($items, 0, 4) as $item) { … } ?>
</div>
<div id="section2">
<?php foreach(array_slice($items, 4) as $item) { … } ?>
</div>
更新
如果$items
不是一个数组,而只是一个实现Iterator的非数组对象,则不能使用这种方法,但可能可以使用LimitIterator
。
<?php
$sectionOneItems = new LimitIterator($items, 0, 4);
$sectionTwoItems = new LimitIterator($items, 4);
?>
<div id="section1">
<?php foreach($sectionOneItems as $item) { … } ?>
</div>
<div id="section2">
<?php foreach($sectionTwoItems as $item) { … } ?>
</div>
如果这也不起作用,那么需要对正在迭代的对象进行更多的内省。
我认为这个函数可能对您有用array_chunk()。http://www.php.net/manual/en/function.array-chunk.php