如何使用 codeigniter 中的参数为 url 创建分页?

how to create pagination for url with parameters in codeigniter?

我们有一个基于某些参数的页面结果的应用程序,例如 domain.com/index.php/welcome/student/male 这里 welcome 是控制器 student 是方法名称 male 是参数,现在我们想要为此分页,但问题是一个人也可以使用这样的子类别 domain.com/index.php/welcome/student/male/steven 其中 steven 是另一个参数,如何为这种类型的 url 创建分页。提前谢谢你:)

我曾使用 codeigniter,但我认为您可能必须使用 config/routes.php。例如:

$route['^(bar1|bar2)/routes/(:any)/(:any)'] = "routes/get_bar//";

您可以像这样在控制器(在本例中为路由)中编写一个函数:

public function get_bar($bar1 = null, $bar2 = null)

希望对你有帮助 问候!

可选参数与分页一起使用时出现的一些问题:

  1. 分页偏移的位置在 URL 中根据 提供的参数数量。
  2. 如果没有设置可选参数, 分页偏移量将作为参数。

方法一:
使用查询字符串进行分页:

function student($gender, $category = NULL) {
    $this->load->library('pagination');
    $config['page_query_string'] = TRUE;
    $config['query_string_segment'] = 'offset';

    $config['base_url'] = base_url().'test/student/'.$gender;
    // add the category if it's set
    if (!is_null($category)) 
        $config['base_url'] = $config['base_url'].'/'.$category;

    // make segment based URL ready to add query strings
    // pagination library does not care if a ? is available
    $config['base_url'] = $config['base_url'].'/?';


    $config['total_rows'] = 200;
    $config['per_page'] = 20;
    $this->pagination->initialize($config);

    // requested page:
    $offset = $this->input->get('offset');

    //...
}

方法二:
假设 category 永远不会是数字,如果最后一段是数值那么它是分页偏移量而不是函数的参数:

function student($gender, $category = NULL) {
    // if the 4th segment is a number assume it as pagination rather than a category
    if (is_numeric($this->uri->segment(4))) 
        $category = NULL;

    $this->load->library('pagination');
    $config['base_url'] = base_url().'test/student/'.$gender;
    $config['uri_segment'] = 4;

    // add the category if it's set
    if (!is_null($category)) {
        $config['uri_segment'] = $config['uri_segment'] + 1;
        $config['base_url'] = $config['base_url'].'/'.$category;
    }

    $config['total_rows'] = 200;
    $config['per_page'] = 20;
    $this->pagination->initialize($config);

    // requested page:
    $offset = ($this->uri->segment($config['uri_segment'])) ? $this->uri->segment($config['uri_segment']) : 1;

    //...
}   

我更喜欢第一种方法,因为它不会干扰函数参数,并且更容易在抽象级别实现分页支持。