Skip to content

Instantly share code, notes, and snippets.

@ronipl
Last active December 27, 2017 12:24
Show Gist options
  • Save ronipl/80f5a8385c59d054e3b57b62dc02aa40 to your computer and use it in GitHub Desktop.
Save ronipl/80f5a8385c59d054e3b57b62dc02aa40 to your computer and use it in GitHub Desktop.
<?php
/*
* Roni Pinili
* 12/17/2017
* Laravel treebuilding (Parent - Child Collection)
Params child collection, parent collection
*/
/*
* Branch Elements
* Params child collection, Parent ID
*/
function buildBranch($branchElements, $parentId)
{
$branch = array();
foreach ($branchElements as $branchElement) {
if ($branchElement['parent_id'] == $parentId) {
$children = buildBranch($branchElements,'');
if ($children) {
$branchElement['children'] = $children;
}
$branch[] = $branchElement;
}
}
return $branch;
}
/*
* Tree Elements
* Params Parent collection, child collection
*/
function buildTree($treeElement, $branchElement)
{
$tree = array();
foreach ($treeElement as $parentCategory) {
array_push($tree, array("parent"=> $parentCategory->name,'children'=>buildBranch($branchElement, $parentCategory->id)));
}
return $tree;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment