PHP递归重写变量
我正在努力使用递归函数,因为它似乎覆盖了foreach循环中的变量。有人能帮我确定如何解决这个问题吗?我试图实现的是一个文件夹树,可以在SQL数据库中找到,父文件夹包含子文件夹和子文件夹。我有孩子,但只有第一个孩子的孙子。我相信它在某处覆盖了这个陈述PHP递归重写变量,php,recursion,Php,Recursion,我正在努力使用递归函数,因为它似乎覆盖了foreach循环中的变量。有人能帮我确定如何解决这个问题吗?我试图实现的是一个文件夹树,可以在SQL数据库中找到,父文件夹包含子文件夹和子文件夹。我有孩子,但只有第一个孩子的孙子。我相信它在某处覆盖了这个陈述 function locateFolders($folderId, $arrIn = array()) { $con = $_SESSION["dbConnection"]->conStr; array_p
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;
}
这花了好几天时间,但我终于弄明白了。我想和大家分享一下,以防其他人也有类似的问题。请注意,代码可能不“正确”,或者可能有更好的方法来实现这一点,但它对我来说是有效的。我在这里调用了几个较小的函数,如果您有问题,这就是原因:
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);
}
警告:您完全可以使用参数化的预处理语句,而不是手动生成查询。它们由或提供。永远不要相信任何形式的输入!即使您的查询仅由受信任的用户执行。使用
die(mysqli_error($conn))是一个非常糟糕的主意
在您的代码中,因为它可能会泄漏敏感信息。有关更多说明,请参阅本文: