andreaem andreaem - 3 months ago 15
PHP Question

PHP get parameters from URL and convert to array

CASE:

I'm trying to get ordered items and quantity from another page, so I'm passing it using GET (http://foo.bar/?view=process-order&itm=1&qty=1000...), then I must to take this parameters and convert to an multidimensional array following this sequence:

EXPECTED:

URL will be: http://foo.bar/?view=foo-bar&itm=1&qty=1000&itm=2&qty=3000&itm=3&qty=1850

[0]=>
[itm]=>'1',
[qty]=>'1000',
[1]=>
[itm]=>'2',
[qty]=>'3000',
[2]=>
[itm]=>'3';
[qty]=>'1850',
etc.


CODE:

$url = $_SERVER['REQUEST_URI']; //get the URL
$items = parse_url($url, PHP_URL_QUERY); //get only the query from URL
$items = explode( '&', $items );//Explode array and remove the &
unset($items[0]); //Remove view request from array
$items = implode(",", $items); //Implode to a string and separate with commas
list($key,$val) = explode(',',$items); //Explode and remove the commas
$items = array($key => $val); //Rebuild array


ACTUAL RESULT:

[itm=1] => [qty=1000]


ACTUAL BEHAVIOUR:

Result leave only the first element in the array and make it like
array({[itm=1]=>[qty=1000]})
that anyway isn't what I need.
Even If I've read much pages of PHP docs can't find the solution.

Thanks to all who can help

Answer

Your statement list($key,$val) = explode(',',$items); will only fetch the first two items in an array.

Here's a rewritten version

$chunks = explode('&', $_SERVER['QUERY_STRING']);
$items = array();
$current = -1; // so that entries start at 0
foreach ($chunks as $chunk) {
  $parts = explode('=', $chunk);
  if ($parts[0] == 'itm') {
    $current++;
    $items[$current]['itm'] = urldecode($parts[1]);
  }
  elseif ($parts[0] == 'qty') {
    $items[$current]['qty'] = urldecode($parts[1]);
  }
}

print_r($items);