我將導航檔案夾結構存盤在 mysql 中:

我有這個導航:

現在我需要自動檢測父級檔案夾并為所有級別的父級檔案夾創建導航資訊欄,但我不知道如何,我只有一級父級。

如何創建回圈并在何時自動parent停止0?
這是我的功能:
public static function Gallery($fid = NULL){
$folder_id = $fid ? $fid : 1;
echo "<div class=\"gallery-c\">";
echo "<div class=\"gallery-path--c\">";
$current_path_obj = Database::dbquery("SELECT * FROM calendar_gallery_folders WHERE id = $fid", false, true)['result'][0];
$current_path_name = $current_path_obj->folder;
$current_path_parent = $current_path_obj->parent;
$parent_path_name = Database::dbquery("SELECT folder FROM calendar_gallery_folders WHERE id = $current_path_parent", false, true)['result'][0]->folder;
// Navigation information bar
echo $parent_path_name."/".$current_path_name;
echo "</div>";
echo "<div class=\"gallery-folder--c\">";
// Folders
foreach(Database::dbquery("SELECT * FROM calendar_gallery_folders WHERE parent = $folder_id ORDER BY id", false, true)['result'] as $folder){
echo "<a class=\"js-gallery-folderlink gallery-folder--box\" data-folder=\"$folder->id\">
<div class=\"gallery-folder--icon\"><span class=\"icon material-symbols-outlined\">folder</span></div>
<div class=\"gallery-folder--text\">$folder->folder</div></a>";
}
echo "</div>";
echo "</div>";
}
uj5u.com熱心網友回復:
您需要獲取陣列中的所有檔案夾并進行遞回回圈。
public static function Gallery($fid = NULL){
$folder_id = $fid ? $fid : 1;
echo "<div class=\"gallery-c\">";
echo "<div class=\"gallery-path--c\">";
$all_folders = Database::dbquery("SELECT * FROM calendar_gallery_folders", false, true)['result'];
//Map result with Key ID
$folders_map = [];
foreach($all_folders as $folder){
$folders_map[$folder->id]=$folder;
}
//Recrusive Loop function to get the trail
$navigation = getTrail($folders_map,$fid);
//Reverse the result
$navigation = array_reverse($navigation);
//Print the navigation
echo implode('/',$navigation)
echo "</div>";
echo "</div>";
}
function getTrail($folder_map,$folder_id,$trail=[]){
if(isset($folder_map[$folder_id])){
array_push($trail,$folder_map[$folder_id]->folder);
}else{
return [];
}
if($folder_map[$folder_id]->parent!=0){
$trail = $this->getTrail($folder_map,$folder_map[$folder_id]->parent,$trail);
}
return $trail;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/486265.html
上一篇:如何定位MySQL資料行
