Created
January 25, 2016 12:59
-
-
Save kirilkirkov/2a06fa2d459d397edb0a to your computer and use it in GitHub Desktop.
Build Tree Structure from array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function getPagesForSpace() { | |
$arr = array(); | |
$result = $this->query("SELECT * FROM pages ORDER BY id ASC"); | |
if($result !== false) { | |
while ($row = $result->fetch_assoc()) { | |
$arr[] = $row; | |
} | |
function buildTree(array $elements, $parentId = 0) { | |
$branch = array(); | |
foreach ($elements as $element) { | |
if($element['sub_for'] == $parentId) { | |
$children = buildTree($elements, $element['id']); | |
if($children) { | |
$element['children'] = $children; | |
} | |
$branch[] = $element; | |
} | |
} | |
return $branch; | |
} | |
return $tree = buildTree($arr); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This simple example will crate something like this:
When table structure is
id <-- parent_id