php 将查询字符串转换为关联数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8324593/
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
Converting a querystring into an associative array
提问by Nicolas Le Thierry d'Ennequin
In PHP, I need a function to convert a querystring from an URL, say: http://example.com?key1=value1&key2=value2
into a PHP associative array : array ['key1' => 'value1', 'key2' => 'value2']
.
在 PHP 中,我需要一个函数来将查询字符串从 URLhttp://example.com?key1=value1&key2=value2
转换为 PHP 关联数组 : array ['key1' => 'value1', 'key2' => 'value2']
。
I've come up to this piece of code. It works, but I find it a bit lengthy. (And PHP has built-in functions for everything: I'm surprised I haven't found anything out-of-the-box, something like the reverse of http_build_query
.)
我想出了这段代码。它有效,但我觉得它有点冗长。(而且 PHP 对所有东西都有内置函数:我很惊讶我没有找到任何开箱即用的东西,类似于http_build_query
.)
Can you suggest a better way to do this?
你能建议一个更好的方法来做到这一点吗?
function getUrlParams($url) {
$querystring = parse_url($url, PHP_URL_QUERY);
$a = explode("&", $querystring);
if (!(count($a) == 1 && $a[0] == "")) {
foreach ($a as $key => $value) {
$b = explode("=", $value);
$a[$b[0]] = $b[1];
unset ($a[$key]);
}
return $a;
} else {
return false;
}
}
回答by 472084
You can get just the atributes from a URL using parse_url()
您可以使用parse_url()从 URL 中获取属性
Once you have that you can use parse_str()to convert them to variables, it works with multidimensional arrays too!
一旦你有了它,你就可以使用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 MNR
If you mean as what you written then it is very simple and don't need anything else there is a predefined Superglobal variable $_GET
in PHP which itself represents all the query string as key, value pairs associative array.
如果你的意思是你写的那么它非常简单并且不需要任何其他东西$_GET
,PHP中有一个预定义的超全局变量,它本身将所有查询字符串表示为键值对关联数组。
Example:
例子:
// current page URI: http://localhost/test.php?key1=value1&key2=value2
echo '<pre>';
print_r($_GET);
echo '</pre>';
Result:
结果:
Array(
[key1] = value1
[key2] = value2
)
For more information about $_GET
PHP superglobal goto: http://php.net/manual/en/reserved.variables.get.php
有关$_GET
PHP 超全局的更多信息,请转到:http: //php.net/manual/en/reserved.variables.get.php
回答by user3454065
$url = 'http://example.com?key1=value1&key2=value2&key3=value3';
preg_match_all('/\w+=.*/',$url,$matches);
parse_str($matches[0][0], $output);
print_r($output);
回答by lup
foreach ($_GET as $key => $value) $arr["$key"]= $value;