Created
July 21, 2021 11:17
-
-
Save fateyan/5a7bea7bdb39ab886cc59a947ba186d1 to your computer and use it in GitHub Desktop.
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 | |
function parseTOC($items) { | |
if (count($items) == 0) return []; | |
reset($items); | |
$stack = array(); | |
$ret = array(); | |
$stack[] = &$ret; | |
$first = array( | |
'level' => current($items)[0], | |
'text' => current($items)[1], | |
'subItems' => [] | |
); | |
$ret[] = &$first; | |
$stack[] = &$first; | |
next($items); | |
while (current($items)) { | |
$cur = array( | |
'level' => current($items)[0], | |
'text' => current($items)[1], | |
'subItems' => [] | |
); | |
if ($cur['level'] < $stack[count($stack)-1]['level']) { | |
while ($stack[count($stack)-1] != $ret && $cur['level'] < $stack[count($stack)-1]['level']) { | |
array_pop($stack); | |
} | |
continue; | |
} | |
if ($cur['level'] == $stack[count($stack)-1]['level']) { | |
array_pop($stack); | |
if ($stack[count($stack)-1] == $ret) { | |
$ret[] = $cur; | |
$stack[] = &$ret[count($ret)-1]; | |
} else { | |
$stack[count($stack)-1]['subItems'][] = $cur; | |
$stack[] = &$stack[count($stack)-1]['subItems'][ count($stack[count($stack)-1]['subItems'])-1 ]; | |
} | |
next($items); | |
continue; | |
} | |
if ($cur['level'] > $stack[count($stack)-1]['level']) { | |
$stack[count($stack)-1]['subItems'][] = $cur; | |
$stack[] = &$stack[count($stack)-1]['subItems'][ count($stack[count($stack)-1]['subItems'])-1 ]; | |
next($items); | |
} | |
} | |
return $ret; | |
} | |
echo json_encode(parseTOC(array( | |
array(1, 'textA'), | |
array(2, 'text'), | |
array(3, 'text'), | |
array(5, 'text'), | |
array(1, 'textB'), | |
array(3, 'text'), | |
array(2, 'text'), | |
array(2, 'text'), | |
array(3, 'text'), | |
)), JSON_PRETTY_PRINT); | |
//echo json_encode(parseTOC(array( | |
// array(1, 'textB'), | |
// array(3, 'text'), | |
// array(2, 'text'), | |
// array(2, 'text'), | |
// array(3, 'text'), | |
//)), JSON_PRETTY_PRINT); | |
/* output: | |
[ | |
{ | |
"level": 1, | |
"text": "textA", | |
"subItems": [ | |
{ | |
"level": 2, | |
"text": "text", | |
"subItems": [ | |
{ | |
"level": 3, | |
"text": "text", | |
"subItems": [ | |
{ | |
"level": 5, | |
"text": "text", | |
"subItems": [] | |
} | |
] | |
} | |
] | |
} | |
] | |
}, | |
{ | |
"level": 1, | |
"text": "textB", | |
"subItems": [ | |
{ | |
"level": 3, | |
"text": "text", | |
"subItems": [] | |
}, | |
{ | |
"level": 2, | |
"text": "text", | |
"subItems": [] | |
}, | |
{ | |
"level": 2, | |
"text": "text", | |
"subItems": [ | |
{ | |
"level": 3, | |
"text": "text", | |
"subItems": [] | |
} | |
] | |
} | |
] | |
} | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment