获取叶子类别的 ID

get IDs of leaf categories

我需要获取所有叶子子类别ID的ID,getLastChildren()的参数是当前类别的ID,我需要它下面的所有叶子。我试过这样的事情,但它以无限循环结束。 $categoryListCategoryItem个对象的容器,它可以return所有的子类,也可以找到当前类的父类。如果当前类别是叶,$category->isLastChild() 将 return 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
    ];
}

这是解决方案:

/**
 * @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;
}