Home > Blockchain >  PHP Category Recursion & Arrays not displaying all results
PHP Category Recursion & Arrays not displaying all results

Time:10-24

I'm using a category system which has parent categories which can have multiple child categories, which can also have child categories and so on... I am trying to use a script which will use the current selected category ID and add all of their children IDs, and their children IDs etc to an array. The recursion works fine, as when I test it with echoing the names/ID's, it shows all of them. Although the array only seems to ever show up to the first set of child categories and no more.

The category database is similar to this:

cat_id     cat_name      cat_parent_id
123        parent1       0
456        child1        123
789        child2        123
101112     child3        123
131415     childa1       456
161718     childa2       456
192021     childb1       789
222324     childb2       789

My current code is as follows:

$childCatsArray = array();
$catsArray = hasChildren($catID, $childCatsArray);


function hasChildren($catID, $array) {

    global $conn;
    
    
    $sql = "SELECT * FROM `SysCategories` WHERE `cat_parent_id` = ?;";

    $stmt = mysqli_stmt_init($conn);
    // bind integer value $parent_id
            
    if(!mysqli_stmt_prepare($stmt, $sql)){
        echo 'SQL ERROR 2';
        return;
    }
                                    
    mysqli_stmt_bind_param($stmt, "s", $catID);
                                    
    mysqli_stmt_execute($stmt);
    $resultData = mysqli_stmt_get_result($stmt);
    while($child = mysqli_fetch_assoc($resultData)){
        $child_cat_id = $child['cat_id'];
        $child_cat_name = $child['cat_name'];
        
        array_push($array, $child_cat_id);
        hasChildren($child_cat_id, $array);
        
    }
    
    return $array;
}

I seem to be only able to add the first set of child categories to the array and never the whole set, no matter how I position the sections of the code and I have no idea why, for example, it will return something like:

Array ( [0] => 123 [1] => 456 [2] => 789 [3] => 101112 )

Any help would be appriciated.

CodePudding user response:

You want to pass your array in by reference.

function hasChildren($catID, &$array)

https://www.php.net/manual/en/language.references.pass.php

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

  • Related