Marcus Purcell Marcus Purcell - 2 months ago 5
PHP Question

PHP function call itself to build an array

Hello I do not know if this is possible, I am trying to build an array but it is not working when using return as it comes back blank but when I do var dump it shows the values...Please here is the code below

public function getURL($category_id,$output=null){

$getCat = ProductCategory::where("id","=",$category_id)->get();
if(count($getCat) != 0){
foreach($getCat as $cat){
$parent = $cat->category_id;
$output[] = $parent;
$this->getURL($parent,$output);
}
} else {
$finish = true;
}

if($finish){
//var_dump($output); this returns what I need
return $output;
}

}


Edit
I am trying to build a list of urls, in my database I have category_id to represent its a sub category. So I am trying to get all the ID's back to build the list of urls

UPDATE

Thanks to @Parziphal he showed me my mistake and fixed it for me. Here is his answer. Thanks everyone for there input too.

public function getURL($categoryId)
{
return $this->getParentIdsRecursive($categoryId, []);
}

protected function getParentIdsRecursive($categoryId, $ids = [])
{
$category = ProductCategory::where("id", $categoryId)->first();

if ($category && $category->category_id) {
$ids[] = $category->category_id;
$ids = $this->getParentIdsRecursive($category->category_id, $ids);
}

return $ids;
}

Answer

I haven't tested this, and I don't understand what you are trying to do, but maybe this works:

public function getURL($categoryId)
{
    return $this->getParentIdsRecursive($categoryId, []);
}

protected function getParentIdsRecursive($categoryId, $ids = [])
{
    $category = ProductCategory::where("id", $categoryId)->first();

    if ($category && $category->category_id) {
        $ids[] = $category->category_id;
        $ids = $this->getParentIdsRecursive($category->category_id, $ids);
    }

    return $ids;
}

If I'm (and the code is) not wrong, that will return all the category ids up to the first parent.

Comments