PHP - 显示foreach循环中的'X'项,其中包含显示下一个'X'项的链接

时间:2010-07-15 18:46:51

标签: php foreach

我有一个循环遍历数组的foreach循环(simpleXML节点)。该数组中可以包含0到几百个项目。我想找到一种方法来显示前10个结果,然后有一个链接显示下10个,依此类推。

例如,我目前有:

$i=0;
$limit=10;
foreach ($nodes as $node){
echo "here is the output: ".$node."<br>\n";
if (++$i >=$limit) break;
}
显然,无论$ nodes数组中有多少项,它只显示前10个。但我想我读过每次循环时foreach循环重置计数器 - 所以如果我想要一个链接说:next 10 itmes - 我不确定如何在index = 10上告诉循环开始。

我甚至在这里咆哮着正确的树吗?

5 个答案:

答案 0 :(得分:5)

这称为分页。您可以使用array_slice提取所需的数组段:http://php.net/array_slice

<?php
$page = isset($_GET['page']) ? intval($_GET['page']) : 0;
$elementsPerPage = 10;
$elements = array_slice($nodes, $page * $elementsPerPage, $elementsPerPage);

foreach($elements as $node)
{
    echo "Here is the output: ".$node."<br>\n";
}

然后你只需要一个指向同一页面的链接?page = $ page + 1

答案 1 :(得分:3)

好吧,你可以使用LimitIterator ...

$offset = (int) (isset($_GET['offset']) ? $_GET['offset'] : 0);
$limit = 10;
$arrayIterator = new ArrayIterator($nodes);
$limitIterator = new LimitIterator($arrayIterator, $offset, $limit);

$n = 0;
foreach ($limitIterator as $node) {
    $n++;
    //Display $node;
}
if ($n == 10) {
    echo '<a href="?offset='.($offset + 10).'">Next</a>';
}

答案 2 :(得分:1)

您应该使用常规for循环

if(count($nodes) < 10) {
   $nnodes = count($nodes);
} else {
   $nnodes = 10;
}

for($i = 0; $i < $nnodes; $i++) {
   echo $nodes[$i];
}

答案 3 :(得分:0)

我有同样的问题,这样解决了

<?php $i=0 ?>
<?php foreach ($nodes as $node) : ?>
<?php $i++ ?>
<?php echo "here is the output: ".$node."<br>\n"; ?>
<?php if ($i == 3) break; ?>
<?php endforeach; ?>

答案 4 :(得分:0)

if ($n++ <= 9) {
echo 'what ever you like to get going';
}