次のような構造が必要になります (正確な仕様については詳しく説明しませんが、再帰に必要なものは次のとおりです)。
table_categories:
- record_id
- parent_id
- category_name
+-----------+-----------+---------------------+
| record_id | parent_id | category_name |
+-----------+-----------+---------------------+
| 1 | NULL | Parent Category 1 |
| 2 | NULL | Parent Category 2 |
| 3 | 1 | Child Category 1 |
| 4 | 3 | Subchild Category 1 |
| 5 | 2 | Child Category 2 |
+-----------+-----------+---------------------+
record_id フィールドと parent_id フィールドを設定してデータベース テーブルをセットアップしたら、次のコードを使用してツリー構造を取得します。
// Create a new class to manage structure generation
class treeStructure
{
// Create a property to store the database records
private $structureData;
// This function will retrieve all records from the database
// We can use PHP to manage the database, rather than relying
// on recursive SQL queries
function getRecords() {
// Generate a db connection
try {
$db = new PDO($dsn, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
}
// Retrieve all the records from the database
$result = $db->prepare("SELECT record_id, parent_id, category_name FROM table_categories");
$result->execute();
// Save the data array to an object property
$this->structureData = $result->fetchAll(PDO::FETCH_ASSOC);
// Return a default true value
return true;
}
// This function will count the number of children for any specified
// parent
function countChildren($parentId = 0){
// Set a default value to return. By default
// Say this element has 0 children
$childCount = 0;
// Loop through each of the results
foreach($this->structureData as $row){
// If the current records parent ID is the same
// as the supplied parent ID, add 1 to the child
// count
if((int)$row['parent_id']===(int)$parentId) {
$childCount += 1;
}
}
// Return the number of children
return $childCount;
}
// This method will generate our HTML tree structure
function generateStructure($parentId = 0) {
// Define a default value for $html
$html = '';
// Loop through the results
foreach($this->structureData as $row){
// If the current records parent ID equals the requested
// parent ID...
if((int)$row['parent_id']==(int)$parentId){
// Add an <li> element
$html .= '<li>' . $row['category_name'];
// Before closing the <li>, check for any children
// If this record does have children, generate a new
// <ul> element, and recall this function with a new
// parent ID
if($this->countChildren($row['record_id']>0)){
$html .= '<ul>';
$html .= $this->generateStructure($row['record_id']);
$html .= '</ul>';
}
// Now close the <li>
$html .= '</li>';
}
}
// Return the generated HTML
return $html;
}
}
$structureObj = new treeStructure();
$structureObj->getRecords();
$html = '<ul>' . $structureObj->generateStructure() . '</ul>';
echo $html;
これは、何が起こるべきかの基本的な概要です。
- 新しい構造体オブジェクトを生成する
- データベースから構造のすべてのレコードを取得し、オブジェクト プロパティに割り当てます
- メソッドを実行し
generateStructure()
、 を渡して$parentId
レコードを取得します
generateStructure()
parent_id
次に、すべてのレコードをループし、渡された ID を持つレコードを探しますgenerateStructure()
- 現在のカテゴリが構造体に追加される
generateStructure()
と、メソッドが呼び出されますcountChildren()
。countChildren()
0 より大きい int を返す場合、現在のレコードには子があるため、別のメニュー要素を生成します
generateStructure()
次に、生成された HTML を返します
上記のコードはデバッグしていません。構文エラーがいくつかある可能性があります。ただし、次のような html が出力されるはずです。
<ul>
<li>Parent Category 1
<ul>
<li>Child Category 1
<ul>
<li>Subchild Category 1</li>
</ul>
</li>
</ul>
</li>
<li>Parent Category 2
<ul>
<li>Child Category 2</li>
</ul>
</li>
</ul>