Jane Yun
Jane Yun

Reputation: 185

splitting up the path portion of a url

i couldn't find anything so i just wanted to take a url and then split it and turn it into key value pairs.

$url = 'http://domain.com/var/1/var2/2';

i am currently using a array_chunk on the path after using a parse_url

$u = parse_url($url);
$decoded = array_chunk($u['path'],2);

but it returns

array (
   [0] => array (
       [0] => var
       [1] => 1
   ),
   [1] => array (
       [0] => var2
       [1] => 2
   )
)

what i would like is

array (
    [var] => 1,
    [var2] => 2
)

is there a Zend Framework method that is available to decode this into an array?

Upvotes: 1

Views: 155

Answers (3)

Shane Stillwell
Shane Stillwell

Reputation: 3258

If you're in the Controller it's simply

$data = $this->_getAllParams();
unset($data['module'], $data['controller'], $data['action']);

$data will now be

array (
    [var] => 1,
    [var] => 2
)

Hopefully you're not POSTing variables as well or this will also include the POST'd variables.

Upvotes: 0

takeshin
takeshin

Reputation: 50688

I'd use request object.

$url = 'http://domain.com/var/1/var2/2';
$request = new Zend_Controller_Request_Http($url);
$params = $request->getParams();
// or
$param = $request->getParam('var', $defaultValueNull);

This has the advantage, that you don't have to use isset to check which keys were set.

Upvotes: 5

Jonah
Jonah

Reputation: 10091

$u = parse_url($url);
$decoded = array_chunk($u['path'],2);
$new = array();
for ($decoded as $pair) {
    $new[$pair[0]] = $pair[1];
}
print_r($new);

outputs

array (
    [var] => 1,
    [var2] => 2
)

Upvotes: 0

Related Questions