Slinidy
Slinidy

Reputation: 387

Get subcategory and subsubcategory and infinite subsubsubcategory

I'm trying to loop a function that takes all subcategorys.. from one main category into one table and put in array.

Example table:

ID   | ParentID
1    | 0
2    | 1
3    | 1
4    | 2
5    | 4
6    | 3
7    | 1

(Subcategories have parentID)

Now the example in function PHP taking all subsubcategories of a main category (ID=1)

    var_dump(getSubCategories(1));

    function getSubCategories($parent_id = 0, $subcategories = array())
    {
        global $db;

        $query = $db->query("
SELECT ID 
  FROM categories
 WHERE ParentID = $parent_id 
 ORDER 
    BY Name ASC
");

        while ($row = $query->fetch_assoc()) {
            $subcategories = getSubCategories($row['ID'], $subcategories);
        }
        return $subcategories;
    }

The problem is to put the IDs inside an array, because the code above prints this result:

array(0) { }

One thing I noticed is that if I add this line below while:

echo $row['ID'] . ',';

It prints the result correctly, but not as an array:

2,3,4,5,6,7

My expectation was like this for example: array(1, 2, 3, 4, 5, 6, 7) etc.. without being multidimensional.

Upvotes: 0

Views: 228

Answers (2)

Nick
Nick

Reputation: 147166

Your problem is that you keep overwriting $subcategories instead of adding to it. Also, you need to add the current $row['ID'] value to the array. You need to change this line:

$subcategories = getSubCategories($row['ID'], $subcategories);

to

$subcategories = array_merge($subcategories, array($row['ID']), getSubCategories($row['ID']);

Upvotes: 1

Payam Mohammadi
Payam Mohammadi

Reputation: 136

You should pass $subcategories parameter by reference

    $subCategories = array();
    getSubCategories(1, $subCategories);
    var_dump($subCategories);
    function getSubCategories(&$subCategories, $parent_id = 0)
    {
        global $db;

        $query = $db->query("
SELECT ID 
  FROM categories
 WHERE ParentID = $parent_id 
 ORDER 
    BY Name ASC
");
        while ($row = $query->fetch_assoc()) {
            getSubCategories($subCategories, $row['ID']);
        }
    }

Or just append the results to $subcategories variable.

    var_dump(getSubCategories(1));
    function getSubCategories($parent_id = 0)
    {
        global $db;

        $query = $db->query("
SELECT ID 
  FROM categories
 WHERE ParentID = $parent_id 
 ORDER 
    BY Name ASC
");
        $subcategories = array();
        while ($row = $query->fetch_assoc()) {
            $subcategories = array_merge($subcategories, getSubCategories($row['ID']));
        }
        return $subcategories;
    }

Upvotes: 2

Related Questions