我有一个数组,在某些索引中包含JSON,我必须解码它
例如:
这是JSON
$json = {"Lavel1":"This is Lavel1","LavelLoop":"{\"Lavel2\":\"This is Lavel2\",\"LavelLoop\":\"{\\\"Lavel3\\\":\\\"This is Lavel3\\\",\\\"LavelLoop\\\":[]}\"}"}
如果是第一次解码,则会给出此数组
$array = json_decode($json);
// this is the output
Array
(
[Lavel1] => This is Lavel1
[LavelLoop] => {"Lavel2":"This is Lavel2","LavelLoop":"{\"Lavel3\":\"This is Lavel3\",\"LavelLoop\":[]}"}
)
所以我已经解码了三次,但我不能假设它包含多少个子json
欲望输出应该是这样的
Array
(
[Lavel1] => This is Lavel1
[LavelLoop] => Array
(
[Lavel2] => This is Lavel2
[LavelLoop] => Array
(
[Lavel3] => This is Lavel3
[LavelLoop] => Array
(
)
)
)
)
我已经尝试过循环,但它没有工作它给我的错误像一些索引显示我空
答案 0 :(得分:1)
我已经更新了答案再看看
$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)
: '';
}
<强>输出强>
Array
(
[Lavel1] => This is Lavel1
[LavelLoop] => Array
(
[Lavel2] => This is Lavel2
[LavelLoop] => Array
(
[Lavel3] => This is Lavel3
[LavelLoop] => Array
(
)
)
)
)
答案 1 :(得分:0)
LaravelLoop
是一个字符串,而不是一个对象。对所有人来说都是如此。删除引号,它将解码正常。