<?php $array = [ "# Grandparent #1", "# Grandparent #2", "## Parent #2-1", "### Child #2-1-1", "## Parent #2-2", "### Child #2-2-1", "### Child #2-2-2", "## Parent #2-3", "## Parent #2-4", "# Grandparent #3", "## Parent #3-1", ]; function recurse(array $lines, int $level = 1): array { $tree = []; $directDescendants = []; foreach($lines as $line) { [$hashes, $name] = explode(' ', $line, 2); $depth = strlen($hashes); if ($depth === $level) { if ($directDescendants) { $parent['children'] = recurse($directDescendants, $level + 1); } $directDescendants = []; // reset collection of direct descendants unset($parent); // destroy reference $parent = ['name' => $name]; // name the member $tree[] = &$parent; // push the reference variable into the tree } elseif ($depth > $level) { $directDescendants[] = $line; // collect only direct descendants of current level parent member } } if ($directDescendants) { $parent['children'] = recurse($directDescendants, $level + 1); } return $tree; } var_export(recurse($array));
You have javascript disabled. You will not be able to edit any code.