foreach 循环的简单分页
我需要对 WordPress 插件生成的输出进行分页.该插件从数据库中检索某个产品组的所有产品.基本代码为:
I need a pagination for the output that is generated by a WordPress plugin. The plugin retrieves all products of a certain productgroup from the datebase. The basic code is:
<?php
foreach ((array)$this->view['data']['produkte'] as $p)
{ ?>
...some html code here
}
?>
其中 $p
是一个多维数组,包含单个产品的数据.我想将输出限制为 10 个产品并为此创建一个简单的分页.该插件非常复杂并使用嵌套模板,因此在这种情况下可能无法选择自定义查询.
where $p
is an multi-dimensional array that contains the data for the single product.
I'd like to limit the output to, say, 10 products and create a simple pagination for that. The plugin is quite complex and uses nested templates, therefore a custom query is probably not an option in this case.
如果有人能指出我正确的方向,那就太好了.谢谢!
Would be great if somebody could point me in the right direction. Thank you!
这是最终代码.非常感谢您的宝贵帮助!!
Here's the final code. Thank you very much for your valuable help!!
<?php
$nb_elem_per_page = 3;
$page = isset($_GET['seite'])?intval($_GET['seite']-1):0;
$data = (array)$this->view['data']['produkte'];
$number_of_pages = intval(count($data)/$nb_elem_per_page)+2;
$page_no = $_REQUEST['seite'];
foreach (array_slice($data, $page*$nb_elem_per_page, $nb_elem_per_page) as $p)
{ ?> some HTML here... <?php } ?>
<?php if (count($data) > $nb_elem_per_page) { ?>
<ul id='paginator'>
<?php
for($i=1;$i<$number_of_pages;$i++){
if ($i == $page_no) {?>
<li><?php echo $i ?></li>
<?php }
else { ?>
<li><a href="<?php echo get_permalink(); ?>?show=<?php echo $_REQUEST['show']; ?>&seite=<?=$i?>"><?php echo $i ?></a></li>
<?php }} ?>
</ul>
<?php { ?>
由于默认 url 已经包含一个查询字符串,我不得不稍微修改一下代码.我不希望当前站点在分页中有链接.这让我得到分页查询字符串的数量:
Since the default url contains already a query string, I had to modify the code a litte bit. I don't want the current site to have a link in the pagination. This gets me the number of the pagination query string:
$page_no = $_REQUEST['seite'];
然后我可以使用简单的 if 语句轻松更改分页链接:
I can then easily change the pagination links with a simple if-statement:
if ($i == $page_no) {...}?>
再次感谢!
推荐答案
你可能需要稍微修改一下,但这将是这样的:
You may have to tinker this around a bit but that will be something like that :
$nb_elem_per_page = 10;
$page = isset($_GET['page'])?intval($_GET['page']-1):0;
$data = (array)$this->view['data']['produkte'];
$number_of_pages = intval(count($data)/$nb_elem_per_page)+1;
<?php foreach (array_slice($data, $page*$nb_elem_per_page, $nb_elem_per_page) as $p) { ?>
...some html code here
<?php} ?>
<ul id='paginator'>
<?php
for($i=1;$i<$number_of_pages;$i++){?>
<li><a href='./?page=<?=$i?>'>$i</a></li>
<?php}?>
</ul>
相关文章