WITH RECURSIVE `cte` AS (
SELECT `id`, `pid`, `name`, 0 AS `level`
FROM `table`
UNION SELECT `p`.`id`, `p`.`pid`, `p`,`name`, `cte`.`level` + 1 AS `level`
FROM `cte`
JOIN `table` AS `p` ON `p`.`id` = `cte`.`pid`
)
SELECT `id`, `name`, `level`
FROM `cte`
ORDER BY `level`
$query = "SELECT id, pid, name FROM your_table";
$result = $mysqli->query($query);
$items = [];
while($row = $result->fetch_assoc()){
$items[$row['id']] = ['pid' => $row['pid'], 'name' => $row['name']];
}
function buildTree(array $elements, $parentId = 0) {
$branch = array();
foreach ($elements as $element) {
if ($element['pid'] == $parentId) {
$children = buildTree($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
$tree = buildTree($items);