我想得到一个子类别的分类树
假设我有一个名为附件的子类别
这个子类别有电子>笔记本电脑的父母。
这就是电子>笔记本电脑>配件
表:
-----------------------------------------
| id | parent_id | name |
|---- |----------- |------------- |
| 1 | 0 | Electronics |
| 2 | 1 | Laptops |
| 3 | 2 | Accessories |
-----------------------------------------我可以得到一个子类别的根类别,例如:
function getTopParent($category) {
if($category->parent_id === null) {
return $category->name;
}
return getTopParent(App\Category::find($category->parent_id));
// Will return Electronics
}此外,我还知道如何显示树、请看这里等类别
function printCategoryName($categories, $parentName = '') {
foreach ($categories as $category) {
$name = $parentName ? implode(' > ', [$parentName, $category->name]) : $category->name;
echo sprintf('%s%s', $name, PHP_EOL);
if (count($category->children) > 0) {
printCategoryName($category->children, $name);
}
}
}
printCategoryName($categories);我需要的是为这个子类别提供一个类似于附件、和get树以及类别树的类别:
电子>笔记本电脑>配件。
我怎样才能做到这一点?
发布于 2020-01-15 10:21:51
我就是这样做的:
function getParentsTree($category, $name)
{
if ($category->parent_id == null)
{
return $name;
}
$parent = Category::find($category->parent_id);
$name = $parent->name . ' > ' . $name;
return getParentsTree($parent, $name);
}
$cat = Category::find(1);
echo getParentsTree($cat, $cat->name);输出:Electronics > Laptops > Accessories
https://stackoverflow.com/questions/59748528
复制相似问题