CodeIgniter 3分页:将$offset传入视图修正文章序号
解决CodeIgniter 3分页后文章序号重置的问题
这问题我之前做后台管理页时也碰到过,分页后每页序号从1开始确实有点不符合用户习惯,咱们只需要把控制器里计算好的$offset传给视图,再调整序号的计算逻辑就搞定了,分两步来:
第一步:将$offset传入视图
在你的控制器index方法里,拿到$offset之后,把它加入到$data数组中,这样视图就能获取到这个偏移量值:
public function index() { $this->load->library('pagination'); $config = [ 'base_url' => base_url("/dashboard/posts"), 'page_query_string' => TRUE, 'query_string_segment' => 'page', 'display_pages' => TRUE, 'use_page_numbers' => TRUE, 'per_page' => 10, 'total_rows' => $this->Posts_model->get_num_rows(), 'uri_segment' => 3, 'first_link' => '«', 'first_tag_open' => '<li>', 'first_tag_close' => '</li>', 'last_link' => '»', 'last_tag_open' => '<li>', 'last_tag_close' => '</li>', 'full_tag_open' => '<ul class="pagination">', 'full_tag_close' => '</ul>', 'next_link' => '›', 'next_tag_open' => '<li>', 'next_tag_close' => '</li>', 'prev_link' => '‹', 'prev_tag_open' => '<li>', 'prev_tag_close' => '</li>', 'num_tag_open' => '<li>', 'num_tag_close' => '</li>', 'cur_tag_open' => '<li class="active"><span>', 'cur_tag_close' => '</span></li>' ]; if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) { $_GET[$config['query_string_segment']] = 1; } $limit = $config['per_page']; $offset = ($this->input->get($config['query_string_segment']) - 1) * $limit; $this->pagination->initialize($config); $data['posts'] = $this->Posts_model->get_posts($limit, $offset); // 新增这一行,把偏移量传给视图 $data['offset'] = $offset; $this->load->view('partials/header', $data); $this->load->view('dashboard/dindex'); $this->load->view('partials/footer'); }
第二步:修改视图中的序号计算逻辑
在视图的循环里,把原来仅依赖循环索引的$index + 1,改成$index + 1 + $offset,这样就能基于当前页的偏移量生成连续的序号:
<table class="table table-striped table-sm border-0"> <thead> <tr> <th>#</th> <th>Title</th> <th>Publication date</th> <th class="text-center">Actions</th> </tr> </thead> <tbody> <?php foreach ($posts as $index => $post): ?> <tr> <!-- 调整序号计算逻辑 --> <td><?php echo $index + 1 + $offset; ?></td> <td><?php echo $post->title; ?></td> <td><?php echo nice_date($post->created_at, 'D, M d, Y'); ?></td> <td class="text-center"> <div class="btn-group btn-group-sm" role="group"> <a href="<?php echo base_url('posts/post/post/') . $post->id; ?>" class="btn btn-success"><i class="fa fa-eye"></i> View</a> <a href="<?php echo base_url('posts/edit/') . $post->id; ?>" class="btn btn-success"><i class="fa fa-pencil-square-o"></i> Edit</a> <a href="<?php echo base_url('posts/delete/') . $post->id; ?>" id="delete_post" class="btn btn-success"><i class="fa fa-trash"></i> Delete</a> </div> </td> </tr> <?php endforeach ?> </tbody> </table> <div class="card-footer bg-white py-1"> <?php $this->load->view("partials/pagination");?> </div>
简单原理说明
$offset是当前页第一条数据在总数据列表中的起始位置(比如第二页时,$offset就是10),循环里的$index是当前页内的索引(0到9),两者相加再+1(因为索引从0开始),就能得到连续的序号——比如第二页的序号就会从11开始,一直到20。
内容的提问来源于stack exchange,提问作者Razvan Zamfir
相关产品推荐
相关产品推荐

