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;
}

花了几天时间,但我终于想明白了。我想分享一下,以防其他人也有类似的问题。注意,该代码可能不是"0";适当的";或者可能有更好的方法,但它对我有效。我有几个较小的函数在这里被调用,所以如果你有问题,这就是为什么:

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);
}

最新更新