开发者

String "array" to real array

Now I got the string of an array, like this :

$str = "array('a'=>1, 'b'=>2)";

How can I convert this string into real array ? Is there any "smart way" to do that, other that use explode() ? Because the "string" array could be ver开发者_如何学Cy complicated some time.

Thanks !


Use php's "eval" function.

 eval("\$myarray = $str;");


i don't know a good way to do this (only evil eval() wich realy should be avoided).

but: where do you get that string from? is it something you can affect? if so, using serialize() / unserialize() would be a much better way.


With a short version of the array json_decode works

json_decode('["option", "option2"]')

But with the old version just like the OP's asking it doesn't. The only thing it could be done is using Akash's Answer or eval which I don't really like using.

json_decode('array("option", "option2")')


You could write the string to a file, enclosing the string in a function definition within the file, and give the file a .php extension.

Then you include the php file in your current module and call the function which will return the array.


You'd have to use eval().

A better way to get a textual representation of an array that doesn't need eval() to decode is using json_encode() / json_decode().


If you can trust the string, use eval. I don't remember the exact syntax, but this should work.

$arr = eval($array_string);

If the string is given by user input or from another untrusted source, you should avoid eval() under all circumstances!

To store Arrays in strings, you should possibly take a look at serialize and unserialize.


Don't use eval() in any case just call strtoarray($str, 'keys') for array with keys and strtoarray($str) for array which have no keys.

function strtoarray($a, $t = ''){
    $arr = [];
    $a = ltrim($a, '[');
    $a = ltrim($a, 'array(');
    $a = rtrim($a, ']');
    $a = rtrim($a, ')');
    $tmpArr = explode(",", $a);
    foreach ($tmpArr as $v) {
        if($t == 'keys'){
            $tmp = explode("=>", $v);
            $k = $tmp[0]; $nv = $tmp[1];
            $k = trim(trim($k), "'");
            $k = trim(trim($k), '"');
            $nv = trim(trim($nv), "'");
            $nv = trim(trim($nv), '"');
            $arr[$k] = $nv;
        } else {
            $v = trim(trim($v), "'");
            $v = trim(trim($v), '"');
            $arr[] = $v;
        }
    }
    return $arr;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜