CodeIgniter Forums
URI - getting segments into associative array with user-defined keys - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: URI - getting segments into associative array with user-defined keys (/thread-25238.html)



URI - getting segments into associative array with user-defined keys - El Forum - 12-05-2009

[eluser]markowe[/eluser]
OK, $this->uri->uri_to_assoc(n) - is great: from a URI like:

Code:
index.php/user/search/name/joe/location/UK/gender/male

we end up with an array like:

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

(taken from the docs)

...BUT I don't really want that great big URI, with the parameter NAMES in - I mean I know which parameter is which. It would make for better code if there was a class that would let me specify parameter names:

$paramNames = array ('name', 'location', 'gender');

and then match the URI segments in corresponding order, using these as key names. That way I would still end up with

Code:
'name' => 'joe'
'location' => 'UK'
'gender' => 'male'

...but from a URI in the form:

Code:
index.php/user/search/joe/UK/male

i.e. without the parameter names appearing in the URI. Then I could use e.g.

Code:
$name = $uriArray ['name'];

...which is obviously nicer than referring to the parameters by segment number.

I am pretty sure there isn't a helper available to achieve this, am I right? Is there any reason for that, if not? I know it would be easy to write, just wondering... Suggestion for a future addition?


URI - getting segments into associative array with user-defined keys - El Forum - 12-05-2009

[eluser]Jamie Rumbelow[/eluser]
There isn't anything like that currently, but it could be easily implemented. The only issue here is where would you put something like this? CodeIgniter's routing system is very simple, so it wouldn't make sense to put it in the routes.php config file. It would be messy if it was inline in the function code. It would be too cumbersome to put in the doccomment or somewhere else in the controller.

Where could it go?


URI - getting segments into associative array with user-defined keys - El Forum - 12-05-2009

[eluser]markowe[/eluser]
What about just expanding uri_to_assoc to take an array as an extra optional parameter, like

Code:
uri_to_assoc (3, array('name', 'location', 'gender'))

so that if this optional array is specified then these keys get assigned to the URI values, if not then the default behaviour is applied. Though that's a bit messy because of the different size URIs depending on the case. Perhaps just another function in the URI class called uri_to_userassoc, or something, which would work as above?