简体   繁体   中英

Parse array in query string as array and not literally “array”

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? ie

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?

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.

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

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM