Created
September 18, 2022 11:52
-
-
Save Adamwaheed/3ca07376f1eaf1d6ed96fed4ee076fee to your computer and use it in GitHub Desktop.
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
<?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