如何在数组中添加 PHP 分页 [英] How to add PHP pagination in array's
本文介绍了如何在数组中添加 PHP 分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试很多方法来添加 PHP 分页.我尝试搜索并尝试找出实现分页的其他方法,但没有一个有效.
I've been trying a lot of ways to add PHP pagination. I have tried searching and trying to figure other ways of implementing the pagination but none of them work.
这是我创建索引页面的方式:
Here's how I created the Index page:
<?php
$menuItems = array(
"post1" => array(
"title" => "Sample Title",
"utime" => "M/d/Y",
"content" => "<p>Body of the post</p>"
),
"post2" => array(
"title" => "Another Sample Title",
"utime" => "M/d/Y",
"content" => "<p>Content goes here...</p>"
),
);
foreach ($menuItems as $contItem => $item) {
?>
<li>
<a href="dish.php?item=<?php echo $contItem; ?>">
<h1><?php echo $item["title"]; ?></h1>
<small><?php echo $item["utime"]; ?></small>
</a>
</li>
<?php } ?>
我想知道如何对数组列表进行分页.谢谢!
I would like to know how I can paginate the the array list. Thanks!
推荐答案
你可以使用简单的PHP函数array_slice()
u can use simple PHP function called array_slice()
$menuItems = array_slice( $menuItems, 0, 10 );
显示前 10 个项目.
show first 10 items.
$menuItems = array_slice( $menuItems, 10, 10 );
显示接下来的 10 个项目.
show next 10 items.
更新:
$page = ! empty( $_GET['page'] ) ? (int) $_GET['page'] : 1;
$total = count( $yourDataArray ); //total items in array
$limit = 20; //per page
$totalPages = ceil( $total/ $limit ); //calculate total pages
$page = max($page, 1); //get 1 page when $_GET['page'] <= 0
$page = min($page, $totalPages); //get last page when $_GET['page'] > $totalPages
$offset = ($page - 1) * $limit;
if( $offset < 0 ) $offset = 0;
$yourDataArray = array_slice( $yourDataArray, $offset, $limit );
更新#2:
分页示例:
$link = 'index.php?page=%d';
$pagerContainer = '<div style="width: 300px;">';
if( $totalPages != 0 )
{
if( $page == 1 )
{
$pagerContainer .= '';
}
else
{
$pagerContainer .= sprintf( '<a href="' . $link . '" style="color: #c00"> « prev page</a>', $page - 1 );
}
$pagerContainer .= ' <span> page <strong>' . $page . '</strong> from ' . $totalPages . '</span>';
if( $page == $totalPages )
{
$pagerContainer .= '';
}
else
{
$pagerContainer .= sprintf( '<a href="' . $link . '" style="color: #c00"> next page » </a>', $page + 1 );
}
}
$pagerContainer .= '</div>';
echo $pagerContainer;
这篇关于如何在数组中添加 PHP 分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文