<?php $array = [ [ 'id' => 196, 'name' => 'Abilități spirituale', 'parent' => 0, 'depth' => 0, 'score' => 0, 'sort' => null, ], [ 'id' => 395, 'name' => 'Date generale', 'parent' => 196, 'depth' => 0, 'score' => 0, 'sort' => 1, ], [ 'id' => 201, 'name' => 'Gândirea pozitivă', 'parent' => 197, 'depth' => 0, 'score' => 0, 'sort' => 1, ], [ 'id' => 202, 'name' => 'Satisfacția personală', 'parent' => 197, 'depth' => 0, 'score' => 0, 'sort' => 2, ], [ 'id' => 203, 'name' => 'Concordanța cu sine', 'parent' => 197, 'depth' => 0, 'score' => 0, 'sort' => 3, ], [ 'id' => 204, 'name' => 'Managementul calitativ al timpului liber', 'parent' => 197, 'depth' => 0, 'score' => 0, 'sort' => 4, ], [ 'id' => 198, 'name' => 'Armonia cu ceilalți', 'parent' => 196, 'depth' => 0, 'score' => 0, 'sort' => 3, ], [ 'id' => 199, 'name' => 'Sensul vieții și misiunea personală', 'parent' => 196, 'depth' => 0, 'score' => 0, 'sort' => 4, ], [ 'id' => 200, 'name' => 'Perspectiva de ansamblu asupra realității', 'parent' => 196, 'depth' => 0, 'score' => 0, 'sort' => 5, ], [ 'id' => 197, 'name' => 'Armonia cu sine', 'parent' => 196, 'depth' => 0, 'score' => 0, 'sort' => 2, ], ]; function getScore(int $id): int { return [ 196 => 0, 197 => 0, 198 => 54, 199 => 49, 200 => 49, 201 => 57, 202 => 38, 203 => 29, 204 => 21, 395 => 0, ][$id] ?? 0; } function buildTree(array &$rows, int $parentId = 0, int $depth = 0): array { $tree = []; foreach ($rows as &$row) { if ($row['parent'] !== $parentId) { continue; } $row['depth'] = $depth; $row['children'] = buildTree($rows, $row['id'], $depth + 1); foreach ($row['children'] as &$child) { $row['score'] += $child['score'] += getScore($child['id']); $child['depth'] = $depth + 1; } $tree[] = $row; } return $tree; } usort( $array, fn($a, $b) => $a['sort'] <=> $b['sort'] ); var_export( buildTree($array) );
You have javascript disabled. You will not be able to edit any code.