1

I am trying to find a way to transform a string type variable into an array type variable. To be more precise, what i am looking for is the change this (example):

$v = "['1', 'a', ['2', 'b', ['3'], 'c']]";

note that this is not a json-formatted string. into this:

$v = ['1', 'a', ['2', 'b', ['3'], 'c']];

Note the double-quotes in the first example, $v is a string, not an array, which is the desired effect.

  • Second hint: `parse` – Tushar Apr 22 '16 at 11:47
  • Possible duplicate of [How to convert JSON string to array](http://stackoverflow.com/questions/7511821/how-to-convert-json-string-to-array) – Cerbrus Apr 22 '16 at 11:48
  • 2
    Single quotes aren't valid in JSON, so that won't help here. If you've got PHP array syntax in a string, you'll need to use eval(), as horrible as that is. – iainn Apr 22 '16 at 11:49
  • That does not have a valid json schema – Nadir Apr 22 '16 at 11:50
  • @iainn you're right, json parse didn't help me at all, and simply using eval on it won't work either. i presume it needs some complex combination of parsing and eval – Mihai Zamfir Apr 22 '16 at 11:50

3 Answers3

3

Simple solution using str_replace(to prepare for decoding) and json_decode functions:

$v = "['1', 'a', ['2', 'b', ['3'], 'c']]";
$converted = json_decode(str_replace("'",'"',$v));

print_r($converted);

The output:

Array
(
    [0] => 1
    [1] => a
    [2] => Array
        (
            [0] => 2
            [1] => b
            [2] => Array
                (
                    [0] => 3
                )

            [3] => c
        )    
)
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
2
$v = "['1', 'a', ['2', 'b', ['3'], 'c']]";

eval("\$v = $v;");

var_dump($v);

PS: make sure $v string doesn't contain unexpected code.

apoq
  • 1,454
  • 13
  • 14
  • 1
    thank you for your answer! the code provided works, but i choose to use Romans' solution to avoid using the eval function – Mihai Zamfir Apr 22 '16 at 12:04
  • You're welcome, and you're right about preferring the json_decode solution over eval. – apoq Apr 22 '16 at 12:08
1

This should work:

$json = "['1', 'a', ['2', 'b', ['3'], 'c']]";
$json = str_replace("'",'"',$json);
$result_array = json_decode($json); // This is your array
granmirupa
  • 2,780
  • 16
  • 27