php 如何将 URL 参数列表字符串分解为成对的 [key] => [value] 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9046279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:02:05  来源:igfitidea点击:

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

phpurlparametersexplode

提问by ProgrammerGirl

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.

使用在 上explode()分隔的常规函数&将分隔参数但不成[key] => [value]对。

Thanks.

谢谢。

回答by knittl

Use PHP's parse_strfunction.

使用 PHP 的parse_str功能。

$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 stringof an URL), you can already access it via the superglobal $_GETarray:

我想知道你从哪里得到这个字符串?如果它是问号之后的 URL 的一部分(URL 的查询字符串),则您已经可以通过超全局$_GET数组访问它:

# 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' )

回答by lorenzo-s

Try to use the parse_str()function:

尝试使用该parse_str()功能:

$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

回答by James L.

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];
}