keeping url parameters during pagination

后端 未结 4 1702
南方客
南方客 2020-11-30 14:03

Is there any way to keep my GET parameters when paginating.

My problem is that I have a few different urls i.e

questions.php?sort=votes&author_i         


        
相关标签:
4条回答
  • 2020-11-30 14:41

    In short, you just parse the URL and then you add the parameter at the end or replace it if it already exists.

    $parts = parse_url($url) + array('query' => array());
    parse_str($parts['query'], $query);
    $query['page'] = $page;
    $parts['query'] = http_build_str($query);
    $newUrl = http_build_url($parts);
    

    This example code requires the PHP HTTP module for http_build_url and http_build_str. The later can be replaced with http_build_query and for the first one a PHP userspace implementation exists in case you don't have the module installed.

    Another alternative is to use the Net_URL2 package which offers an interface to diverse URL operations:

    $op = new Net_URL2($url);
    $op->setQueryVariable('page', $page);
    $newUrl = (string) $op;
    

    It's more flexible and expressive.

    0 讨论(0)
  • 2020-11-30 14:47

    How about storing your page parameter in a session, so you don't have to modify every single page url?

    0 讨论(0)
  • 2020-11-30 14:50

    If you wanted to write your own function that did something like http_build_query, or if you needed to customize it's operations for some reason or another:

    <?php 
    function add_edit_gets($parameter, $value) { 
        $params = array(); 
        $output = "?"; 
        $firstRun = true; 
        foreach($_GET as $key=>$val) { 
            if($key != $parameter) { 
                if(!$firstRun) { 
                    $output .= "&"; 
                } else { 
                    $firstRun = false; 
                } 
                $output .= $key."=".urlencode($val); 
             } 
        } 
    
        if(!$firstRun) 
            $output .= "&"; 
        $output .= $parameter."=".urlencode($value); 
        return htmlentities($output); 
    } 
    
    ?>
    

    Then you could just write out your links like:

    <a href="<?php echo add_edit_gets("page", "2"); ?>">Click to go to page 2</a>
    
    0 讨论(0)
  • 2020-11-30 15:04

    You could use http_build_query() for this. It's much cleaner than deleting the old parameter by hand.

    It should be possible to pass a merged array consisting of $_GET and your new values, and get a clean URL.

    $new_data = array("currentpage" => "mypage.html");
    $full_data = array_merge($_GET, $new_data);  // New data will overwrite old entry
    $url = http_build_query($full_data);
    
    0 讨论(0)
提交回复
热议问题