Parse query string into an array

2018-12-31 08:53发布

How can I turn a string below into an array?

pg_id=2&parent_id=2&document&video 

This is the array I am looking for,

array(
    'pg_id' => 2,
    'parent_id' => 2,
    'document' => ,
    'video' =>
)

9条回答
何处买醉
2楼-- · 2018-12-31 08:55

There are several possible methods, but for you, there is already a builtin parse_str function

$array = array();
parse_str($string, $array);
var_dump($array);
查看更多
ら面具成の殇う
3楼-- · 2018-12-31 08:56

If you're having a problem converting a query string to an array because of encoded ampersands

&

then be sure to use html_entity_decode

Example:

// Input string //
$input = 'pg_id=2&parent_id=2&document&video';

// Parse //
parse_str(html_entity_decode($input), $out);

// Output of $out //
array(
  'pg_id' => 2,
  'parent_id' => 2,
  'document' => ,
  'video' =>
)
查看更多
何处买醉
4楼-- · 2018-12-31 09:01

Using parse_str().

$str = 'pg_id=2&parent_id=2&document&video';
parse_str($str, $arr);
print_r($arr);
查看更多
浪荡孟婆
5楼-- · 2018-12-31 09:05

Use http://us1.php.net/parse_str

Attention, it's usage is:

parse_str($str, &$array);

not

$array = parse_str($str);
查看更多
十年一品温如言
6楼-- · 2018-12-31 09:08

Sometimes parse_str() alone is note accurate, it could display for example:

$url = "somepage?id=123&lang=gr&size=300";

parse_str() would return:

Array ( 
    [somepage?id] => 123 
    [lang] => gr 
    [size] => 300 
)

It would be better to combine parse_str() with parse_url() like so:

$url = "somepage?id=123&lang=gr&size=300";
parse_str( parse_url( $url, PHP_URL_QUERY), $array );
print_r( $array );
查看更多
冷夜・残月
7楼-- · 2018-12-31 09:08

You can use the PHP string function parse_str() followed by foreach loop.

$str="pg_id=2&parent_id=2&document&video";
parse_str($str,$my_arr);
foreach($my_arr as $key=>$value){
  echo "$key => $value<br>";
}
print_r($my_arr);
查看更多
登录 后发表回答