php - 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;
}
解决方案
花了几天时间,但我终于想通了。我想分享一下,以防其他人有类似的问题。请注意,代码可能不“正确”,或者可能有更好的方法来执行此操作,但它对我有用。我在这里调用了几个较小的函数,所以如果你有问题,这就是为什么:
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);
}
推荐阅读
- python - 从 Python 服务运行进程并在服务重启后使其保持活动状态
- ionic-framework - 在移动应用程序中不使用 Ionic 组件的缺点
- android - Android中的加泰罗尼亚语和巴斯克语字符串未使用
- android - 具有多个声明的 Koin 范围?
- azure-devops - 用户无法在 Azure DevOps 中更改通知的联系人电子邮件地址
- c++ - VB.NET 中的 C++ dll - 结构兼容性
- python - 基于来自其模型类的对象的通用查询方法
- ms-access - 通过 MS-Access 中的表单输入数据 - 保留字段 1 并允许多次更新字段 2
- c# - 具有十六进制或 RGB 的一种颜色代码。以此为基础,需要根据 C# 中的百分比生成更亮和更暗的渐变颜色
- react-native - 如何在注销时从反应本机抽屉导航器中删除屏幕(卸载组件)?如何重新加载组件数据?