Skip to content

Instantly share code, notes, and snippets.

@Adamwaheed
Created September 18, 2022 11:52
Show Gist options
  • Save Adamwaheed/3ca07376f1eaf1d6ed96fed4ee076fee to your computer and use it in GitHub Desktop.
Save Adamwaheed/3ca07376f1eaf1d6ed96fed4ee076fee to your computer and use it in GitHub Desktop.
<?php
namespace App\Services;
use App\Models\Entity;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
class EntityTree
{
public $array = [];
public $temp = [];
/**
* @param array $elements
* @param int $parentId
* @return array
*/
public function build(array $elements, $parentId = null): array
{
$branch = array();
$child = array();
foreach ($elements as $element) {
if ($element['parent_id'] == $parentId) {
$children = $this->build($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$child = Arr::add($element, 'children', array());
$branch[] = $child;
}
}
return $branch;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment