Incrementing Operator in Foreach Loop for Pagination

久未见 提交于 2019-12-25 04:59:16

问题


I'm using CodeIgniter Pagination class to paginate my data 10 rows per page. I'm using foreach loop for that.

My problem is, the loop incrementing operator is reset back to 1 in the second, third & next pagination pages.

Page 1 screenshot [dummy data only]:

Page 2 screenshot [dummy data only]:

Page 3 screenshot [dummy data only]:

My controller:

<?php

class Mypagination extends CI_Controller{
    function index(){

        $this->load->database();
        $this->load->library('pagination');

        $config['base_url'] = '/codeigniter/index.php/mypagination/index/';
        $config['total_rows'] = $this->db->get('tracking')->num_rows();
        $config['per_page'] = 10;

        $config['next_link'] = 'Next';
        $this->pagination->initialize($config);

        $data['query'] = $this->db->get('tracking', $config['per_page'], $this->uri->segment(3));
        $this->load->view('mypagination_view', $data);

    }
}

My view:

<?php

$i = 1;

foreach($query->result() as $row){
    echo $i++ . ') ';
echo $row->name . ' - ' . $row->email;
echo '<br>';
}

echo $this->pagination->create_links();

?>

I want that incrementing operator to continue in the next pagination pages like 11,12,13... in the second page. 21,22,23 in the third page...

How to fix this?

Sorry if this is too basic question. I'm just new with CodeIgniter and PHP.


回答1:


In your view :

$links = $this->pagination->create_links();
$i = 1 + $this->pagination->cur_page*$this->pagination->per_page;

foreach($query->result() as $row){
   echo $i++ . ') ';
   echo $row->name . ' - ' . $row->email;
   echo '<br>';
}

echo $links;

and you're cool.

Also, i'd recommend you use less echo, and only for php parts of your templating. For example, your code could be reformatted like this:

<?php $links = $this->pagination->get_links(); ?>

<ol start="<?php echo 1 + $this->pagination->cur_page*$this->pagination->per_page; ?>" >
<?php foreach($query->result() as $row) : ?>
   <li><?php echo $row->name . ' - ' . $row->email; ?></li>
<?php endforeach; ?>
</ol>

<?php echo $links; ?>

Looks cleaner now, i think.




回答2:


Do you use sessions? Perhaps something like this:

<?php

$i = $this->session->userdata('increment') ? $this->session->userdata('increment') : 1;

foreach($query->result() as $row){
  echo $i++ . ') ';
  echo $row->name . ' - ' . $row->email;
  echo '<br>';
}

echo $this->pagination->create_links();
$this->session->set_userdata('increment', $i);

?>


来源:https://stackoverflow.com/questions/21116050/incrementing-operator-in-foreach-loop-for-pagination

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!