字符串数组转为PHP级数组

时间:2021-07-18 11:31:28

先要把字符串处理一下,成为php定义数组的形式,再用eval执行:

$str="
Array
(
[15] => Array
(
[id] => 2304
[fromtype] => item
)
[16] => Array
(
[id] => 2313
[fromtype] => item
)
[17] => Array
(
[id] => 4265
[fromtype] => item
)
)";

$str=preg_replace('/\[([a-z]+)\]\s*=>\s*([0-9a-z]+)/',"'\$1'=>'\$2',",$str);
$p=array('Array','[',']',' )');
$to=array('array',"'","'",'),');
$str=str_replace($p,$to,$str);
//echo $str;

eval("\$arr = ".$str.'; ');
print_r($arr[15]);