I would like to convert array string like
[["a","b",["c1","c2"]],"d",["e1","e2"]]
into an array in PHP.
Is there any way to do that?
I would like to convert array string like
[["a","b",["c1","c2"]],"d",["e1","e2"]]
into an array in PHP.
Is there any way to do that?
The provide string is valid JSON - thus json_decode
can be used to turn it into a real (PHP) array.
Taken almost directly from the documentation (only the string was changed):
$json = '[["a","b",["c1","c2"]],"d",["e1","e2"]]';
var_dump(json_decode($json));
For this case it's significantly cleaner and safer than trying to hack it with other code evaluators (i.e. eval
) and simpler than writing custom parsing code.
Possible duplicate of How to "flatten" a multi-dimensional array to simple one in PHP? and How to Flatten a Multidimensional Array?
The easiest/nicest solution to me is
function flatten(array $array) {
$return = array();
array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
return $return;
}