将查询字符串转换为关联数组 [英] Converting a querystring into an associative array

查看:47
本文介绍了将查询字符串转换为关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PHP 中,我需要一个函数来从 URL 转换查询字符串,例如:http://example.com?key1=value1&key2=value2 到 PHP 关联数组:array ['key1' =>'value1', 'key2' =>'value2'].

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 对所有东西都有内置函数:我很惊讶我没有找到任何开箱即用的东西,类似于 http_build_query 的反面.)

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.)

你能提出更好的方法吗?

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

推荐答案

您可以使用 parse_url()

一旦你有了它,你就可以使用 parse_str() 将它们转换为变量,它也适用于多维数组!

Once you have that you can use parse_str() to convert them to variables, it works with multidimensional arrays too!

$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

这篇关于将查询字符串转换为关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆