ThSorn ThSorn - 6 months ago 16
JSON Question

How to convert string of JSON array to array of object in PHP

suppose I have

$obj = "[{'A':'a1','B':2,'C':'c1'},{'A':'a2','B':2,'C':'c2'}]"


And I want to convert it to array of object.

obj[0](
A => 'a1'
B => 2
C => 'c1'
)


How can I do?

Answer

Use str_replace() to change single quotes to double quote for proper json string.

Then use json_decode() to convert it into array.

$obj = "[{'A':'a1','B':2,'C':'c1'},{'A':'a2','B':2,'C':'c2'}]";
$newobj = str_replace("'", '"', $obj);
$arr = json_decode($newobj);
print_r($arr);

Output

Array
(
    [0] => stdClass Object
        (
            [A] => a1
            [B] => 2
            [C] => c1
        )

    [1] => stdClass Object
        (
            [A] => a2
            [B] => 2
            [C] => c2
        )

)

Check Demo : Click Here

Comments