首页 > 解决方案 > PHP递归覆盖变量

问题描述

我正在努力使用递归函数,因为它似乎覆盖了 foreach 循环中的变量。有人可以帮我确定如何解决这个问题吗?我想要完成的是在 SQL 数据库中找到的文件夹树,其中父文件夹包含子和孙子。我要生孩子,但只有第一个孩子的孙子孙女。我相信它在某处覆盖了声明。

function locateFolders($folderId, $arrIn = array()) {
    $con = $_SESSION["dbConnection"]->conStr;
    array_push($arrIn, $folderId);
    // Select all folders that have this id as the parent folder id
    $statement = "SELECT * FROM folders WHERE parentid='$folderId'";
    $result = mysqli_query($con, $statement) or die(mysqli_error($con));
    
    if (mysqli_num_rows($result) > 0) {
        while ($r = mysqli_fetch_assoc($result)) {
            array_push($arrIn, $r["id"]);
            $statement2 = "SELECT * FROM folders WHERE parentid='".$r["id"]."'";
            $result2 = mysqli_query($con, $statement) or die(mysqli_error($con));
            while ($row = mysqli_fetch_assoc($result2)) {
                return locateFolders($row["id"], $arrIn);
            }
        }
    }
    $arrIn = array_unique($arrIn);

    return $arrIn;
}

标签: phprecursion

解决方案


花了几天时间,但我终于想通了。我想分享一下,以防其他人有类似的问题。请注意,代码可能不“正确”,或者可能有更好的方法来执行此操作,但它对我有用。我在这里调用了几个较小的函数,所以如果你有问题,这就是为什么:

    function findAllFolders($parentId, $folderList = array()) {
    /// This function finds all the user's allowed directories and returns an array of id's.
    /// Starting with the parentId, all directories within are added to the array.
    // Is the folder valid?
    if ($parentId > 1) { // The smallest folder id in my database is 1
        // Does it still exist in the Database?
        if (!mysqli_num_rows(select("folders","id=$parentId")) > 0) {
            return false;
        }
        // If so, add it to the array.
        array_push($folderList, $parentId);
        // Find all folders that have this as its parent folder.
        $subfolders = select("folders", "parentid=$parentId");
        
        if (mysqli_num_rows($subfolders) > 0) {
            while ($row = mysqli_fetch_assoc($subfolders)) {
                array_push($folderList, $row["id"]);
            }
        }
    }
    foreach ($folderList as $folder) {
        $result = select("folders", "parentid=$folder");
        while ($row = mysqli_fetch_assoc($result)) {
            if (!in_array($row["id"],$folderList)) {
                return findAllFolders($row["id"],$folderList);
            }
        }
    }

    // Remove all duplicates.
    array_unique($folderList);
    return $folderList;
}
///HELPER FUNCTION:
function select($table, $condition="1", $columns="*") {
    $sql = "SELECT $columns FROM $table WHERE $condition";
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    // note: $conStr is a global variable connection I created for my program.
    return mysqli_query($conStr, $sql);
}

推荐阅读