Skip to content

Instantly share code, notes, and snippets.

@andyg2
Created August 27, 2019 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andyg2/1ce2f5b750f18b011befd8bb02401ac2 to your computer and use it in GitHub Desktop.
Save andyg2/1ce2f5b750f18b011befd8bb02401ac2 to your computer and use it in GitHub Desktop.
Full circle jquery sortable structure to flat array and back to nested.
<?php
//updated gist for additional array wrapping and empty children arrays (required)
$json = '[{
"name": "Item 1",
"id": 0,
"children": [
[]
]
}, {
"name": "Item 3",
"id": 2,
"children": [
[]
]
}, {
"name": "Item 4",
"id": 3,
"children": [
[{
"name": "Item 3.1",
"id": 8,
"children": [
[]
]
}, {
"name": "Item 2",
"id": 1,
"children": [
[]
]
}, {
"name": "Item 3.2",
"id": "3-1",
"children": [
[]
]
}, {
"name": "Item 3.3",
"id": "3-2",
"children": [
[]
]
}, {
"name": "Item 3.4",
"id": "3-3",
"children": [
[]
]
}, {
"name": "Item 3.5",
"id": "3-4",
"children": [
[]
]
}, {
"name": "Item 3.6",
"id": "3-5",
"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){
$s['children'][0]=[];
$pid = $s['parent'];
unset($s['parent']);
unset($s['order']);
if($pid==0){
$nested[] = &$s;
}else{
if(isset($flat[$pid])){
if (!isset($flat[$pid]['children'])){
$flat[$pid]['children'][0] = [];
}
$flat[$pid]['children'][0][] = &$s;
}
}
}
return $nested;
}
function make_flat($list,$parent){
$r=[];
foreach($list as $ct => $arr){
if(!empty($arr)){
if(isset($arr['id'])){
$ct++;
$r[$arr['id']] = $arr;
$r[$arr['id']]['parent'] = $parent;
$r[$arr['id']]['order'] = $ct;
if(isset($arr['children'][0])){
unset($r[$arr['id']]['children']);
$r = $r + make_flat($arr['children'][0],$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