Code:
CREATE TABLE `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) NOT NULL DEFAULT '0',
`category` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
-----------------------------------------------------------
INSERT INTO `categories` (`id`, `parent_id`, `category`) VALUES
(1, 0, 'General'),
(2, 0, 'PHP'),
(3, 0, 'HTML'),
(4, 3, 'Tables'),
(5, 2, 'Functions'),
(6, 2, 'Variables'),
(7, 3, 'Forms');
PHP Code:
public function generateTree(array $data, int $parent = 0, int $depth = 0): string
{
$tree = "<ul>\n";
for ($i=0, $ni=count($data); $i < $ni; $i++) {
if ($data[$i]['parent_id'] == $parent) {
$tree .= "<li>\n";
$tree .= $data[$i]['category'];
$tree .= generateTree($data, $data[$i]['id'], $depth+1);
$tree .= "</li>\n";
}
}
$tree .= "</ul>\n";
return $tree;
}
What did you Try? What did you Get? What did you Expect?
Joined CodeIgniter Community 2009. ( Skype: insitfx )