Last active
November 17, 2018 06:47
-
-
Save tilhom/eef1b6566afd4c958222432249632fcf 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
function getCategories($categories, &$result, $parent_id = 0, $depth = 0) | |
{ | |
//filter only categories under current "parent" | |
$cats = $categories->filter(function ($item) use ($parent_id) { | |
return $item->parent_id == $parent_id; | |
}); | |
//loop through them | |
foreach ($cats as $cat) | |
{ | |
//add category. Don't forget the dashes in front. Use ID as index | |
$result[$cat->id] = str_repeat('-', $depth) . $cat->title; | |
//go deeper - let's look for "children" of current category | |
getCategories($categories, $result, $cat->id, $depth + 1); | |
} | |
} | |
//get categories data. In this case it's eloquent. | |
$categories = Category::get(); | |
//if you don't have the eloquent model you can use DB query builder: | |
//$categories = DB::table('categories')->select('id', 'parent_id', 'title')->get(); | |
//prepare an empty array for $id => $formattedVal storing | |
$result = []; | |
//start by root categories | |
getCategories($categories, $result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment