我需要创建一些返回类别和子类别数组的函数,其中子类别可以包含多个父类。我试图解决这个问题大概6天,但互联网上什么都没有。
以下是我创建的一些代码,但它不起作用。
private function getAllSubs($category, $index, $parent = null)
{
$subs = $this->database->table('eshop_product_categoryo')
->where('parent', $category->id);
$haveSub = false;
foreach($subs as $sub)
{
$haveSub = true;
break;
}
if($haveSub)
{
$mainCategory = $this->database->table('eshop_product_categoryo')
->where('category', $category->id);
$isMainCategory = true;
foreach($mainCategory as $main)
{
$isMainCategory = false;
break;
}
$ppp = 0;
if(!$isMainCategory)
{
$ppp = $parent;
}
$this->someArray[] = array
(
'name' => $category->name,
'parent' => $ppp,
'index' => $index,
'id' => $category->id
);
foreach($subs as $sub)
{
$ctgry = $this->database->table('eshop_product_category')
->where('id', $sub->category)
->fetch();
$this->getAllSubs($ctgry, ($index+1), $sub->parent);
}
}
}
答案 0 :(得分:0)
好吧终于解决了...... ;-)这里几乎是最终的版本
private function getAllSubs($category, $index)
{
$subs = $this->database->table('eshop_product_categoryo')
->where('otec', $category->id);
$hasSub = false;
foreach($subs as $sub){$hasSub = true; break;}
if($hasSub)
{
$this->someArray[] = array
(
'name' => $category->name,
'index' => $index
);
foreach($subs as $sub)
{
$parent = $this->database->table('eshop_product_category')
->where('id', $sub->category)
->fetch();
$this->getAllSubs($parent, ($index + 1));
}
}
else
{
$this->someArray[] = array
(
'name' => $category->name,
'index' => $index
);
}
}