Created
May 1, 2020 10:40
-
-
Save danyal14/7c8439572d9b6cc43130486ec27b8ea7 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
$categories = [ | |
[ | |
'name' => 'cat1', | |
'children' => [ | |
[ | |
'name' => 'cat1', | |
'children' => [ | |
[ | |
'name'=>'subcat1', | |
'children'=> [] | |
] | |
] | |
] | |
] | |
] | |
] | |
function list_categories(Array $categories) | |
{ | |
$data = []; | |
foreach($categories as $category) | |
{ | |
$data[] = [ | |
'name' = $category->name, | |
'children' = list_categories($category->children), | |
]; | |
} | |
return $data; | |
} | |
$array_categories = list_categories($root_categories); | |
Example for tree categories | |
<?php | |
use Illuminate\Database\Eloquent\Collection; | |
class Tree extends Collection { | |
/** | |
* Build tree structure from the collection. | |
* | |
* @return static | |
*/ | |
public function buildTree() | |
{ | |
$structure = $this->matchNodes(); | |
$this->clean($structure); | |
return $structure; | |
} | |
/** | |
* Match child nodes with the parents. | |
* | |
* @return static | |
*/ | |
protected function matchNodes() | |
{ | |
$structure = new static($this->items); | |
foreach ($this->items as $key => $node) | |
{ | |
$parentId = $node->getParentId(); | |
$nodeId = $node->getKey(); | |
if ($parentId) | |
{ | |
$parent = $structure->find($parentId) | |
->subtree | |
->add($node); | |
} | |
} | |
return $structure; | |
} | |
/** | |
* Clean root level of the structure. | |
* | |
* @param static $structure | |
* @return void | |
*/ | |
protected function clean($structure) | |
{ | |
foreach ($structure as $key => $node) | |
{ | |
if ($node->getParentId()) | |
{ | |
$structure->forget($key); | |
} | |
} | |
} | |
... | |
} | |
<?php | |
class Node extends \Eloquent { // might be used as a trait as well | |
protected $subtree; | |
public function getSubtreeAttribute() | |
{ | |
return $this->subtree = $this->subtree ?: $this->newCollection(); | |
} | |
public function newCollection(array $models = array()) | |
{ | |
return new Tree($models); | |
} | |
... | |
} | |
Then all you need is this: | |
$tree = Category::all()->buildTree(); | |
$tree->toArray(); | |
// nice tree structure of your category objects |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment