PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
CREATE TABLE `networks_groups` ( `group_id` int NOT NULL AUTO_INCREMENT, `parent_id` int DEFAULT NULL, `name` varchar(255) NOT NULL, PRIMARY KEY (`group_id`), UNIQUE KEY `ng_unique_group_name` (`name`), KEY `ng_parent_group_id` (`parent_id`), CONSTRAINT `ng_parent_group_id_fk` FOREIGN KEY (`parent_id`) REFERENCES `networks_groups` (`group_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB; INSERT INTO `networks_groups` (`group_id`, `parent_id`, `name`) VALUES (1, NULL, 'Saint-Gobain'), (2, 1, 'Sekurit'), (3, 2, 'Noyon'), (4, 2, 'Aniche'), (5, 1, 'Abbrasives'), (6, 5, 'Kolow');
Copy Clear
Copy Format Clear
<?php $query = "SELECT * FROM networks_groups;"; $stmt = $pdo->prepare($query); $stmt->execute(); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($rows as $row) { printf("%s\n", implode("\t", $row)); } function buildTreeNative(array $nodes, $parentId = null) { return array_reduce( array_filter( $nodes, fn ($node) => $node['parent_id'] === $parentId ), fn($tree, $node) => [ ...$tree, ...[ $node, ['children' => buildTreeNative($nodes, $node['group_id'])] ] ], [] ); } $tree = buildTreeNative($rows); var_dump($tree);
Show:  
Copy Clear