gpt4 book ai didi

php - Laravel 将所有父类别显示为特定子类别的树

转载 作者:行者123 更新时间:2023-12-05 03:56:02 25 4
gpt4 key购买 nike

我正在尝试获取子类别的类别树

假设我有一个名为Accessories

的子类别

此子类别有电子>笔记本电脑

所以是电子产品 > 笔记本电脑 > 配件

表格:

-----------------------------------------
| 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

}

我还知道如何显示类别,如树,see here

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);

我需要的是给一个像 Accessories 这样的类别并获取树并获取该子类别的类别树:

电子产品 > 笔记本电脑 > 配件

我怎样才能做到这一点?

最佳答案

    protected function getCategoriesTree()
{
$categories = Category::where('parent_id',0)->get();

if($categories->count())
{
foreach ($categories as $category)
{
$categories_tree[$category->id] = $this->getChildCategories($category);
}
}

return response()->json(['categories' => $categories_tree]);
}

private function getChildCategories($category)
{
$sub_categories = [];

$childs = Category::where('parent_id', $category->id)->get();

$sub_categories = $category;

$sub_categories['sub_categories'] = [];

if($childs->count())
{
$sub_categories['sub_categories'] = $childs;
}

return $sub_categories;
}

关于php - Laravel 将所有父类别显示为特定子类别的树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59748528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com