配列があります。その構造は次のとおりです:
$json = '[{"id":27,"children":[{"id":28,"children":[{"id":30},{"id":29}]}]},{"id":31},{"id":32}]';$arry = json_decode($json,true);
$json = '[{"id":27,"children":[{"id":30,"children":[{"id":31}]}]},{"id":28,"children":[{"id":29}]},{"id":32}]';$arry = json_decode($json,true);
Array ([0] => Array ( [id] => 27 [level] => 0 [parent] => 0 )[1] => Array ( [id] => 30 [level] => 1 [parent] => 27 )[2] => Array ( [id] => 31 [level] => 2 [parent] => 30 )[3] => Array ( [id] => 28 [level] => 0 [parent] => 0 )[4] => Array ( [id] => 29 [level] => 1 [parent] => 28 )[5] => Array ( [id] => 32 [level] => 0 [parent] => 0 ) )
$json = '[{"id":27,"children":[{"id":30,"children":[{"id":31}]}]},{"id":28,"children":[{"id":29}]},{"id":32}]';$arry = json_decode($json,true);print_r(foo($arry));function foo($ar, $level=0, $parent=0, &$res=array()) { foreach($ar as $v) { $t = array(); $v['level'] = $level; $v['parent'] = $parent; if(isset($v['children'])) { $t = $v['children']; unset($v['children']); } $res[] = $v; if($t) foo($t, $level+1, $v['id'], $res); } return $res;}
Array( [0] => Array ( [id] => 27 [level] => 0 [parent] => 0 ) [1] => Array ( [id] => 30 [level] => 1 [parent] => 27 ) [2] => Array ( [id] => 31 [level] => 2 [parent] => 30 ) [3] => Array ( [id] => 28 [level] => 0 [parent] => 0 ) [4] => Array ( [id] => 29 [level] => 1 [parent] => 28 ) [5] => Array ( [id] => 32 [level] => 0 [parent] => 0 ))
$json = '[{"id":27,"children":[{"id":30,"children":[{"id":31}]}]},{"id":28,"children":[{"id":29}]},{"id":32}]';$arry = json_decode($json,true);print_r(foo($arry));function foo($ar, $level=0, $parent=0, &$res=array()) { foreach($ar as $v) { $t = array(); $v['level'] = $level; $v['parent'] = $parent; if(isset($v['children'])) { $t = $v['children']; unset($v['children']); } $res[] = $v; if($t) foo($t, $level+1, $v['id'], $res); } return $res;}
Array( [0] => Array ( [id] => 27 [level] => 0 [parent] => 0 ) [1] => Array ( [id] => 30 [level] => 1 [parent] => 27 ) [2] => Array ( [id] => 31 [level] => 2 [parent] => 30 ) [3] => Array ( [id] => 28 [level] => 0 [parent] => 0 ) [4] => Array ( [id] => 29 [level] => 1 [parent] => 28 ) [5] => Array ( [id] => 32 [level] => 0 [parent] => 0 ))