Last active
July 8, 2023 02:16
-
-
Save andyg2/c31dc51dcbc77e9d0f88de2ac0566eb3 to your computer and use it in GitHub Desktop.
Full circle nestable js structure to flat array and back to nested.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$json = '[{ | |
"id": 8, | |
"text": 8, | |
"children": [{ | |
"id": 3, | |
"text": 3, | |
"children": [{ | |
"id": 1, | |
"text": 1, | |
"children": [] | |
}, { | |
"id": 6, | |
"text": 6, | |
"children": [{ | |
"id": 4, | |
"text": 4, | |
"children": [] | |
}, { | |
"id": 7, | |
"text": 7, | |
"children": [] | |
} | |
] | |
} | |
] | |
}, { | |
"id": 10, | |
"text": 10, | |
"children": [{ | |
"id": 14, | |
"text": 14, | |
"children": [{ | |
"id": 13, | |
"text": 13, | |
"children": [] | |
} | |
] | |
} | |
] | |
} | |
] | |
}]'; | |
// parse json to php array | |
$list = json_decode($json,true); | |
pre($list); | |
// flatten array to add parent and order | |
$flat = make_flat($list,0); | |
pre($flat,'flat'); | |
// parse flat array to recreate nested strucure | |
$nested = make_nested($flat); | |
pre($nested,'nested'); | |
//convert back to json | |
echo json_encode($nested); | |
function make_nested($flat) { | |
$nested=[]; | |
foreach($flat as &$s){ | |
if($s['parent']==0){ | |
$nested[] = &$s; | |
}else{ | |
$pid = $s['parent']; | |
unset($s['parent']); | |
unset($s['order']); | |
if(isset($flat[$pid])){ | |
if (!isset($flat[$pid]['children'])){ | |
$flat[$pid]['children'] = []; | |
} | |
$flat[$pid]['children'][] = &$s; | |
} | |
} | |
} | |
return $nested; | |
} | |
function make_flat($list,$parent){ | |
$r=[]; | |
foreach($list as $ct => $arr){ | |
$ct++; | |
$r[$arr['id']] = $arr; | |
$r[$arr['id']]['parent'] = $parent; | |
$r[$arr['id']]['order'] = $ct; | |
if(isset($arr['children'])){ | |
unset($r[$arr['id']]['children']); | |
$r = $r + make_flat($arr['children'],$arr['id']); | |
} | |
} | |
return $r; | |
} | |
function pre($a,$h=false){ | |
echo $h ? '<h3 style="margin-bottom: 0px;">'.$h.'</h3><pre style="margin-top: 0px;">' : '<pre style="margin-top: 0px;">'; | |
print_r($a); | |
echo '</pre>'; | |
} | |
function prex($a,$h=false,$dbg=false){ | |
pre($a,$h); | |
exit; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Parent/Child array structure conversion
This converts between single layer (parent notation) and nested (children notation) array structures
flat
nested