How to explode URL parameter list string into paired [key] => [value] Array? [duplicate]

家住魔仙堡 提交于 2019-12-02 13:52:01

问题


Possible Duplicate:
Parse query string into an array

How can I explode a string such as:

a=1&b=2&c=3

So that it becomes:

Array {
 [a] => 1
 [b] => 2
 [c] => 3
}

Using the regular explode() function delimited on the & will separate the parameters but not in [key] => [value] pairs.

Thanks.


回答1:


Use PHP's parse_str function.

$str = 'a=1&b=2&c=3';
$exploded = array();
parse_str($str, $exploded);
$exploded['a']; // 1

I wonder where you get this string from? If it's part of the URL after the question mark (the query string of an URL), you can already access it via the superglobal $_GET array:

# in script requested with http://example.com/script.php?a=1&b=2&c=3
$_GET['a']; // 1
var_dump($_GET); // array(3) { ['a'] => string(1) '1', ['b'] => string(1) '2', ['c'] => string(1) '3' )



回答2:


Try to use the parse_str() function:

$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz



回答3:


Something like this will work

$str = "a=1&b=2&c=3"
$array = array();
$elems = explode("&", $str);
foreach($elems as $elem){
    $items = explode("=", $elem);
    $array[$items[0]] = $items[1];
}


来源:https://stackoverflow.com/questions/9046279/how-to-explode-url-parameter-list-string-into-paired-key-value-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!