User97798 User97798 - 1 month ago 6
JSON Question

How to json decode a multi dimensional array

I have an array which contain JSON in some index which i have to decode it

For Example:

This is JSON

$json = {"Lavel1":"This is Lavel1","LavelLoop":"{\"Lavel2\":\"This is Lavel2\",\"LavelLoop\":\"{\\\"Lavel3\\\":\\\"This is Lavel3\\\",\\\"LavelLoop\\\":[]}\"}"}


If is decode it first time then it give this array

$array = json_decode($json);

// this is the output
Array
(
[Lavel1] => This is Lavel1
[LavelLoop] => {"Lavel2":"This is Lavel2","LavelLoop":"{\"Lavel3\":\"This is Lavel3\",\"LavelLoop\":[]}"}
)


So i have decode it three times but i can't assume how many sub json it contain




Desire output should be like this


Array
(
[Lavel1] => This is Lavel1
[LavelLoop] => Array
(
[Lavel2] => This is Lavel2
[LavelLoop] => Array
(
[Lavel3] => This is Lavel3
[LavelLoop] => Array
(
)
)
)
)


I have tried loop but it not working it giving me bug like some index shown me empty

Answer

I have updated the answer have a look again

$json = '{"Lavel1":"This is Lavel1","LavelLoop":"{\"Lavel2\":\"This is Lavel2\",\"LavelLoop\":\"{\\\"Lavel3\\\":\\\"This is Lavel3\\\",\\\"LavelLoop\\\":[]}\"}"}';

$array = nested_jsonDecode($json, true);

print_r($array);


function nested_jsonDecode($string, $is_array = true){
    return is_bool($is_array) 
        ? json_decode(str_replace(['\\','"[',']"','"{', '}"'], ['','[',']','{', '}'],$string), $is_array)
        : '';
}

Output

Array
(
    [Lavel1] => This is Lavel1
    [LavelLoop] => Array
        (
            [Lavel2] => This is Lavel2
            [LavelLoop] => Array
                (
                    [Lavel3] => This is Lavel3
                    [LavelLoop] => Array
                        (
                        )

                )

        )

)