在codeigniter中如何通过名称获取uri段?

在codeigniter中如何通过名称获取uri段?

问题描述:

I have the latest codeigniter version, and was wondering how can i get the segments in a url by their parameter name. For instance, here is a sample url:

www.somewebsitedomain.com/param1=something/param2=somethingelse/

now lets say i want to get the value for 'param1', which is 'something', how would i do so using the uri class?

Because by default the uri class only gets segments by number, or the order in which they appear, but i want to get segments by the parameter name in that segment. Or in general just get the parameter value. Hope that makes sense...

我有最新的codeigniter版本,并想知道如何通过参数名称获取url中的段。 例如,这是一个示例网址: p>

  www.somewebsitedomain.com/param1=something/param2=somethingelse/
  code>  pre> 
 \  n 

现在假设我想得到'param1'的值,这是'某事',我怎么会这样使用uri类? p>

因为默认情况下uri class只按编号或它们出现的顺序获取段,但我想通过该段中的参数名称获取段。 或者通常只获取参数值。 希望有道理...... p> div>

You could do $this->uri->uri_to_assoc(n) which will give something like the following

[array]
 (
'name' => 'joe'
'location'  => 'UK'
'gender'    => 'male'
)

Then just just the param name you would like.

Source: http://codeigniter.com/user_guide/libraries/uri.html

You could actually put them as GET vars and use the Input Class:

$param = $this->input->get('param1'); // something

or you can do:

$params = $this->input->get(); // array('param1' => 'something', 'param2' => 'somethingelse')

to get all the parameters

I'm not sure this is what you're asking, but in many applications, URLs follow the form www.domain.com/controller/method/key1/value1/key2/value2. So I decided to extend the CI_URI class to return the value of any "key".

If you put this in your application/core folder, in a file named, MY_URI.php, it extends the built-in URI class:

class MY_URI extends CI_URI {

    /* call parent constructor */
    function __construct() {
        parent::__construct();
    }

    /* return value of the URI segment
       which immediately follows the named segment */
    function getNamed($str=NULL) {

        $key = array_search($str, $this->segments);

        if ($key && isset($this->segments[$key+1])) {
            return $this->segments[$key+1];
        }

        return false;

    }

}

Then if your URLs are in the form

www.somewebsitedomain.com/param1/something/param2/somethingelse/

you can call this function as follows:

$this->uri->getNamed('param1) - returns "something"

$this->uri->getNamed('param2) - returns "somethingelse"