jx12345
jx12345

Reputation: 1670

PHP Recursive Function to Retrieve List of Sub Categories

I'm using Opencart. Categories are stored in a category table with primary key category_id and a field parent_id that signifies the parent category.

Given a category_id I wont to be able to update the price of all products by a certain percentage.

If I can get a list of all the category_ids that are the sub categories or sub-sub categories or sub-sub-sub, etc. it should be fairly straight forward to use these to run the price updates.

I know there's a lot of examples of building php array tree structures with recursive functions similar to this

public function getTree($parent_category_id) {
    $arr = array();
    $sql = "select * from bs_category where parent_id = '$parent_category_id'";
    $query = $this->db->query($sql);
    foreach ($query->rows as $row) {
       $arr[] = array(
         "Parent" => $row["category_id"],
         "Children" => $this->getTree($row["category_id"])
       );
     }
     return $arr;
  }

but this gives me a tree structure of the form

Array
(
    [0] => Array
        (
            [Parent] => 568
            [Children] => Array
                (
                    [0] => Array
                        (
                            [Parent] => 571
                            [Children] => Array
                                (
                                    [0] => Array
                                        (
                                            [Parent] => 572
                                            [Children] => Array
                                                (
                                                )

                                        )

                                )

                        )

                )

        )

Whereas all I want is a simple list eg.

array(568, 571, 572)

I can't seem to get a simple list of all the category_ids without weird duplicates, etc... tbh recursions all blows my mind a bit...

Any help much appreciated.

Upvotes: 1

Views: 2668

Answers (1)

Kep
Kep

Reputation: 5857

You seem to want a simple one-dimensional array (eg. a list) with the sub-category-ids, what you're currently building is a tree (nested arrays). This should to the trick:

public function getList($parentId)
{
    $retVal = array($parentId);

    $query = "SELECT * FROm `bs_category` WHERE `parent_id` = ".$parentId;
    $result = $this->db->query($query);

    foreach($result->rows as $row)
    {
        $retVal = array_merge($retVal, $this->getList($row["category_id"]));
    }

    return $retVal;
}

Upvotes: 3

Related Questions