简体   繁体   English

将带方括号的字符串转换为 PHP 数组

[英]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?如何将此字符串转换为 PHP 数组?

That's a JSON string representation of an array, use json_decode() :这是一个数组的JSON字符串表示,使用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.如果它有任何{ }将是一个对象并在 PHP 中解码为stdClass对象,除非您将true传递给json_decode()以强制使用数组。

Since it's structured as a PHP array (as of PHP 5.4), this works as well (don't use eval on untrusted data).由于它被构造为一个 PHP 数组(从 PHP 5.4 开始),这也能正常工作(不要对不受信任的数据使用eval )。 There is absolutely no reason to do this, it's just illustrative :绝对没有理由这样做,这只是说明性的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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