PHP Convert string into array

谁都会走 提交于 2019-12-12 04:22:27

问题


How to convert a string $string = 'array(array("a"=>"content"))'; (<-- this is string) into array like this:

array(1) { [0]=> array(1) { ["a"]=> string(7) "content" } }

I am going to build a function to run serialize online:

Input: $string = 'array(array(1))'; echo serialize($string);

Result: a:1:{i:0;a:1:{i:0;i:1;}} NOT s:16:"array(array(1)))";

You call: $returnValue = serialize('array(array(1))');


回答1:


You /could/ use eval():

$string = 'array(array("a"=>"content"))';
eval("\$array = $string;");
print_r($array);

Output:

Array
(
    [0] => Array
        (
            [a] => content
        )

)

But if you're accepting user inputs, you should not use eval().

Also, consider using json_encode() / json_decode() instead.

Alternatively, to store arrays in strings, you could use serialize and unserialize.




回答2:


eval? check http://php.net/manual/en/function.eval.php

take note on the Caution the manual shows...



来源:https://stackoverflow.com/questions/18162754/php-convert-string-into-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!