简体   繁体   中英

Convert String with square brackets to PHP Array

I have a string, values are in brackets and separated with comma, like array string:

Example:

[[["Name" , "ID"] , [12]] , ["Test" , 78] , 0]

How to convert this string to PHP array?

That's a JSON string representation of an array, use json_decode() :

$array = json_decode($string);    
print_r($array);

Yields:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Name
                    [1] => ID
                )
            [1] => Array
                (
                    [0] => 12
                )
        )
    [1] => Array
        (
            [0] => Test
            [1] => 78
        )
    [2] => 0
)

If it had any { } that would be an object and decoded as a stdClass object in PHP unless you pass true to json_decode() to force an array.

Since it's structured as a PHP array (as of PHP 5.4), this works as well (don't use eval on untrusted data). There is absolutely no reason to do this, it's just illustrative :

eval("\$array = $string;");
print_r($array);

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