Passing multiple optional parameter/value pairs wi

2019-04-15 09:58发布

问题:

Say user is going to search on 4 or 5 fields, ok? eg. he might want to search by firstname, email, mobile or even page number

I want that codeigniter's url be like this:

site.com/Controller/Method/variable1/value1/variable2/value2/variable3/value3

or

site.com/Controller/Method/variable2/value2/variable3/value3/variable1/value1

(that they should have the same result)

or in this format

site.com/Controller/Method/variable2/value2/variable4/value4

some examples to clarify my question:

site.com/user/search/firstname/John/mobile/123/page/2

or:

site.com/user/search/lastname/Smith/email/gmail.com

In one sentence: I don't want to force the user to use a specific order when setting value to parameters.

回答1:

You can use the _remap function on the controller.

function _remap( $method, $params )
{
    $map = array();
    for( $i = 1; $i < count( $params ); $i = $i + 2 )
    {
        $map[$params[$i-1]] = $params[$i];
    }

    if( $method[0] != '_' && method_exists( $this, $method ))
        return $this->$method( $map );
}

If you want to use it across all your controllers, you would be better to write a custom controller to extend CI_controller with this function, and have all your controllers extend that.



回答2:

I'd pass all the parameters as 1 string with separators eg. /username|alunr#category|99 etc. and find the values from there using php's explode() function.