類別樹 尋求從資料庫中取出類別樹的最高效的辦法

2021-04-02 09:19:45 字數 1618 閱讀 8003

如果要對資料庫進行n*n次的查詢才能取出多級類別的樹,這是個糟糕的解決辦法。

梅花雪的解決辦法是一次取出,多次利用。我受到啟發。他在客戶端完成這個操作。然而字串是在伺服器端生成的。

我的做法是在伺服器端將資料分兩次從庫里取出,用兩個交叉索引的陣列來存放物件。然後對這兩個陣列進行正則查詢的操作,分級找出,生成類別選單字串

資料表和css還有我都打包了。

<?php

//$q = "select concat_ws( '_', id , pid) as indexkey , concat_ws('_' , title , link , published , ordering , access , params  ) as valuekey  from #__collector_menu where access>=0 ";

/*** 共計查詢資料庫兩次,使用concat_ws函式兩次

* 使用正則搜陣列一次(n條記錄)*n次(n*x條記錄)*(n*x)次(y條記錄,依次類推)。

* 對於2級類,則是 2資料庫+1*n次正則。

* 如果用資料庫,則是1資料庫 * n次資料庫。

* 如果用陣列遍歷,則是1資料庫(y條記錄)+n*y+(y-n)次數組迴圈。

** 不知道哪個效率更高。

*/$q = "select concat_ws( '_', id , pid) as indexkey , id , pid ,  title , link , published , ordering , access , params   from #__collector_menu where access>=0 ";

$database->setquery($q);

$rowsindex = $database->loadresultarray(0,'id','indexkey'); //prt($rowsindex);

$rows = $database->loadassoclist( 'indexkey'); //prt($rows);

/* 搜出所有的頂級類別 */

$reg = "#([0-9]+)_0#i";

$mainindex=preg_grep($reg,$rowsindex); //prt($mainindex);

/* 為每乙個頂級類別找出其子類別 */

foreach ($mainindex as $mkey=>$vk) ',$rows[$vk]['title'],$mainitem);

$sub='';

/* 在索引陣列裡找出下級類別 */

$reg = "#([0-9]+)_".$mkey."#i";

$subindex=preg_grep($reg,$rowsindex); //prt($subindex);

/* 如果找到 */

if(count($subindex))//遍歷字項結束

$sub .="/n";

}//end if

$mainitem = str_replace('',$sub,$mainitem);

echo $mainitem;

}function mainitemtpl()

eod;

return $maintpl;

}//end func

?>

資料庫故障類別

語句錯誤 單個資料庫操作 選擇 插入 更新或刪除 失敗。使用者程序錯誤 單個資料庫會話失敗。網路故障 與資料庫的連線斷開。使用者錯誤 使用者成功完成了操作,但是操作不正確 刪除了表,或輸入了錯誤資料 例項錯誤 資料庫例項意外關閉。介質故障 丟失了乙個或多個資料庫檔案 也就是說,檔案已刪除或磁碟出現了...

資料庫語言類別

dml data manipulation language 資料庫操作語言,它們是select update insert delete,就象它的名字一樣,這4條命令是用來對資料庫裡的資料進行操作的語言 ddl data definition language 資料庫定義語言,主要的命令有crea...

資料庫複製的類別

資料庫複製,即 將資料複製到其他伺服器上,並將其儲存在多個節點上。在此過程中,資料庫例項從乙個節點轉移到另一節點,並進行了精確的複製。資料複製用於提高資料可用性,這是 ha 的一項關鍵功能。通常有乙個完整的資料庫例項,或者一些經常使用或所需的物件被複製到另一台伺服器。複製提供了資料庫的多個一致副本,...