我需要获取所有leaf-children类别ID的ID,getLastChildren()
的参数是当前类别的ID,我需要它下面的所有叶子。我试过这样的东西,但结果是无限循环。 $categoryList
是CategoryItem
个对象的容器,可以返回所有子类别,也可以查找当前类别的父级。如果当前类别为leaf,则$category->isLastChild()
将返回true / false。谢谢你的帮助。
/**
* @param int $idCategory
* @return int[]
*/
public function getLastChildren($idCategory)
{
$categoryList = $this->getCategoryList();
$categories = $categoryList->getChildCategories($idCategory);
$leafCats = [];
$nonLeafCats = [];
foreach ($categories as $category) {
$nonLeafCats[] = $category->getId();
}
while (!empty($nonLeafCats)) {
foreach ($nonLeafCats as &$nonLeafCat) {
$categories = $categoryList->getChildCategories($nonLeafCat);
$result = $this->getChildren($categories);
$leafCats = array_merge($leafCats, $result['leafs']);
$nonLeafCats = array_merge($nonLeafCats, $result['nonLeafs']);
unset($nonLeafCat);
}
}
return $leafCats;
}
/**
* @param CategoryItem[] $categories
* @return array
*/
private function getChildren(array $categories)
{
$leafCats = $nonLeafCats = [];
foreach ($categories as $category) {
if ($category->isLastChild()) {
$leafCats[] = $category->getId();
} else {
$nonLeafCats[] = $category->getId();
}
}
return [
'leafs' => $leafCats,
'nonLeafs' => $nonLeafCats
];
}
答案 0 :(得分:0)
这是解决方案:
/**
* @param int $idCategory
* @return int[]
*/
public function getLastChildren($idCategory)
{
if(empty($this->categoryList)) {
$this->categoryList = $this->getCategoryList();
}
$categories = $this->categoryList->getChildCategories($idCategory);
$leafs = [];
foreach ($categories as $category) {
if ($category->isLastChild()) {
$leafs[] = $category->getId();
} else {
$leafs = array_merge($leafs, $this->getLastChildren($category->getId()));
}
}
return $leafs;
}