简体   繁体   English

PHP从URL获取参数并转换为数组

[英]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: 我试图从另一个页面获取订购的物品和数量,所以我使用GET( http://foo.bar/?view=process-order&itm=1&qty=1000 ..。 )传递它,那么我必须采取以下参数,并按照以下顺序转换为多维数组:

EXPECTED: 预期:

URL will be: http://foo.bar/?view=foo-bar&itm=1&qty=1000&itm=2&qty=3000&itm=3&qty=1850 网址为: 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. 结果仅保留数组中的第一个元素,并使其像array({[itm=1]=>[qty=1000]}) ,无论如何我都不需要。 Even If I've read much pages of PHP docs can't find the solution. 即使我已经阅读了很多PHP文档页面也找不到解决方案。

Thanks to all who can help 感谢所有能提供帮助的人

Your statement list($key,$val) = explode(',',$items); 您的语句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);

Here is another version. 这是另一个版本。 I only modified the bottom part of your code (first 4 lines are untouched). 我只修改了代码的底部(未修改前4行)。

$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

$list = array(); // create blank array for storing data
foreach ($items as $item){
    list($key, $val) = explode('=', $item);
    if ($key === 'itm')
        $list[] = ['itm' => $val];
    else // qty
        $list[count($list) - 1]['qty'] = $val;
}

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM