簡體   English   中英

獲取具有父類別名稱和ID的類別樹

[英]get category tree with name and id of parent category

我有id, name, parent數據庫表categories

我目前使用以下方式創建導航欄:

$rsCategories = mysql_query("SELECT * FROM categories WHERE hide = '0' ORDER BY parent, id");

$arrayCategories = array();

while($row = mysql_fetch_assoc($rsCategories)){ 
    $arrayCategories[$row['id']] = array("parent" => $row['parent'], "name" => $row['name']);   
}

function createTree($array, $currentParent, $currLevel = 0, $prevLevel = -1) {

    foreach ($array as $categoryId => $category) {

        if ($currentParent == $category['parent']) {                        

            if ($currLevel > $prevLevel) echo " <ul> "; 

            if ($currLevel == $prevLevel) echo " </li> ";

            echo '<li id="'.$categoryId.'"><a href="/categorie/'. strtolower(str_replace(" ", '_', $category['name'])) .'-'. $categoryId .'/">'. $category['name'] .'</a>';

            if ($currLevel > $prevLevel) { $prevLevel = $currLevel; }

            $currLevel++; 

            createTree ($array, $categoryId, $currLevel, $prevLevel);

            $currLevel--;               
        }   

    }

    if ($currLevel == $prevLevel) echo " </li>  </ul> ";

}`

I need to get full link on third category level like

`href="/category_1/subcaegory_4/ssubcategory_2/"`

For second category level the link should be

`href="/category_1/subcategory_4/"`

and for first level

`href="/category_1/"`

I have tried with `LEFT OUTER JOIN`

`$rsCategories = mysql_query("SELECT *, c.name AS name, c.parent AS parent, c.id AS id, c1.name AS c1_name FROM categories c LEFT OUTER JOIN categories c1 ON c1.id = c.parent WHERE c.hide = '0' AND c1.hide = '0' ORDER BY c.parent, c.id");

但是不行...

謝謝!

您將需要一個這樣的結構(我不會詳細說明確切的規范,但是遞歸需要什么):

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;

這是應該發生的情況的基本概述:

  1. 生成一個新的結構對象
  2. 從數據庫中獲取結構的所有記錄,並分配給對象屬性
  3. 運行generateStructure()方法,傳遞$parentId以獲取以下記錄
  4. 然后generateStructure()遍歷所有記錄,並查找傳遞給generateStructure()的id為parent_id的記錄
  5. 將當前類別添加到結構后, generateStructure()將調用方法countChildren() 如果countChildren()返回的int大於0,則當前記錄有子級,因此我們生成另一個菜單元素
  6. 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM