Reputation: 24122
I have come across a unusual scenario where I need to turn a query string into an array.
The query string comes across as:
?sort%5B0%5D%5Bfield%5D=type&sort%5B0%5D%5Bdir%5D=desc
Which decodes as:
sort[0][field]=type&sort[0][dir]=desc
How do I get this into my PHP as a usable array? i.e.
echo $sort[0][field] ; // Outputs "type"
I have tried evil eval() but with no luck.
I need to explain better, what I need is the literal string of sort%5B0%5D%5Bfield%5D=type&sort%5B0%5D%5Bdir%5D=desc to come into my script and stored as a variable, because it will be passed as a parameter in a function.
How do I do that?
Upvotes: 0
Views: 444
Reputation: 701
Use parse_str()
http://php.net/manual/en/function.parse-str.php
<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
vecho $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
?>
Upvotes: 0
Reputation: 943645
PHP will convert that format to an array for you.
header("content-type: text/plain");
print_r($_GET);
gives:
Array
(
[sort] => Array
(
[0] => Array
(
[field] => type
[dir] => desc
)
)
)
If you mean that you have that string as a string and not as the query string input into your webpage, then use the parse_str
function to convert it.
header("content-type: text/plain");
$string = "sort%5B0%5D%5Bfield%5D=type&sort%5B0%5D%5Bdir%5D=desc";
$array = Array();
parse_str($string, $array);
print_r($array);
… gives the same output.
Upvotes: 2