Skip to content

Instantly share code, notes, and snippets.

@iron-viper
Created April 18, 2016 22:43
Show Gist options
  • Save iron-viper/555f52dcefbf89db34001100fd14bf42 to your computer and use it in GitHub Desktop.
Save iron-viper/555f52dcefbf89db34001100fd14bf42 to your computer and use it in GitHub Desktop.
<?php
$tree = [
[
"id" => "1",
"name" => "test 1",
"parent" => null,
"_children" => [
[
"id" => "1.1",
"name" => "test 1.1",
"parent" => "1",
"_children" => [
[
"id" => "1.1.1",
"parent" => "1.1",
"name" => "test 1.1.1"
],
[
"id" => "1.1.2",
"parent" => "1.1",
"name" => "test 1.2"
],
[
"id" => "1.1.3",
"parent" => "1.1",
"name" => "test 1.3"
]
]
],
[
"id" => "1.2",
"parent" => "1",
"name" => "test 1.2"
],
[
"id" => "1.3",
"parent" => "1",
"name" => "test 1.3"
],
[
"id" => "1.4",
"parent" => "1",
"name" => "test 1.4"
]
]
],
[
"id" => "2",
"name" => "test 2",
"parent" => null,
"_children" => [
[
"id" => "2.1",
"parent" => "2",
"name" => "test 2.1"
],
[
"id" => "2.2",
"parent" => "2",
"name" => "test 2.2"
],
[
"id" => "2.3",
"parent" => "2",
"name" => "test 2.3"
],
[
"id" => "2.4",
"parent" => "2",
"name" => "test 2.4"
]
]
],
[
"id" => "3",
"name" => "test 3",
"parent" => null,
]
];
function printTree($tree, $parent = null)
{
$has_children = false;
foreach ($tree as $element) {
if ($element["parent"] == $parent) {
echo $element["id"] . " => " . $element["name"];
if (isset($element["_children"])) {
$has_children = true;
echo "<div class='children'>";
printTree($element["_children"], $element["id"]);
echo "</div>"; }
}
}
if($has_children){
echo "</div>";
}
}
printTree($tree);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment