Skip to content

Instantly share code, notes, and snippets.

@vordan
Last active February 5, 2023 09:13
Show Gist options
  • Save vordan/3c9c9e23ce5219f225def4750eeb540b to your computer and use it in GitHub Desktop.
Save vordan/3c9c9e23ce5219f225def4750eeb540b to your computer and use it in GitHub Desktop.
Build a tree from a flat array in PHP
<?php
//--------------------------------------------------------
// Example:
//
// $cars = [
// ['id' => 999, 'value' =>'CARS', 'parent_id' => 0 ],
// ['id' => 11, 'value' =>'Toyota', 'parent_id' => 999],
// ['id' => 1, 'value' =>'Avalon', 'parent_id' => 11 ],
// ['id' => 2, 'value' =>'Corolla', 'parent_id' => 11 ],
// ['id' => 3, 'value' =>'Camry', 'parent_id' => 11 ],
// ['id' => 20, 'value' =>'Skoda', 'parent_id' => 999],
// ['id' => 21, 'value' =>'Octavia', 'parent_id' => 20 ],
// ['id' => 22, 'value' =>'Superb', 'parent_id' => 20 ],
// ['id' => 211, 'value' =>'Diesel', 'parent_id' => 22 ],
// ['id' => 212, 'value' =>'Gasoline', 'parent_id' => 22 ],
// ];
//
// $tree = buildTree($cars);
//
// echo "<pre>";
// print_r($tree);
// echo "<pre>";
//--------------------------------------------------------
function buildTree(array &$elements, $parent_id = 0) {
$branch = array();
foreach ($elements as $element) {
if ($element['parent_id'] == $parent_id) {
$children = buildTree($elements, $element['id']);
if ($children) {
$element['data'] = $children;
}
$branch[] = $element;
unset($elements[$element['id']]);
}
}
return $branch;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment