-5

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?

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • array string? what do you want as a result? ["a", "b", "c1", "c2", "d", "e1", "e2"]? – Alexander Kuzmin Jun 28 '13 at 00:15
  • This is quite likely a duplicate http://stackoverflow.com/questions/526556/how-to-flatten-a-multi-dimensional-array-to-simple-one-in-php – MadDogMcNamara Jun 28 '13 at 00:17
  • I can't understand the downvotes. The question is an interesting problem about parsing strings to produce nested arrays in memory. I'm new in SO, but I'm guessing that people just didn't understand the question. – Racso Jun 28 '13 at 00:23
  • "give me the code" questions often get down voted, we expect people to show some effort to solve their own question first –  Jun 28 '13 at 00:25
  • My question should be voted down! I actually though this way, but the real json was an invalid format, then json_decode returned nothing => So I didnt think this is a valid json string. – Dao Hoang Thanh Jun 28 '13 at 09:43

2 Answers2

4

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.

user2246674
  • 7,621
  • 25
  • 28
  • 1
    Why is `eval` in your answer? `eval` is never the right answer. – Halcyon Jun 28 '13 at 00:18
  • 1
    @FritsvanCampen I think eval deserves to be mentioned precisely because it has been used for similar tasks (this question was not originally tagged json). I've updated the wording to try and make it more .. obvious. Also, note that there is not a link to `eval`. – user2246674 Jun 28 '13 at 00:22
0

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;
}
Community
  • 1
  • 1
Alexander Kuzmin
  • 1,120
  • 8
  • 16