简体   繁体   English

获取具有父类别名称和ID的类别树

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

I have database table categories with id, name, parent 我有id, name, parent数据库表categories

I currently create navigation bar with: 我目前使用以下方式创建导航栏:

$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");

but is not work... 但是不行...

Thanks! 谢谢!

You'll need a structure like this (I wont detail the exact specifications, but what is needed for recursion): 您将需要一个这样的结构(我不会详细说明确切的规范,但是递归需要什么):

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    |
 +-----------+-----------+---------------------+

Once you have your database table setup with the record_id and parent_id fields set up, use this code to get the tree structure: 在设置了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;

This is a basic overview of what should happen: 这是应该发生的情况的基本概述:

  1. Generate a new structure object 生成一个新的结构对象
  2. Get ALL records of the structure from the database, and assign to an object property 从数据库中获取结构的所有记录,并分配给对象属性
  3. Run the generateStructure() method, passing the $parentId to get records of 运行generateStructure()方法,传递$parentId以获取以下记录
  4. generateStructure() then loops through all the records and looks for records with parent_id of the id passed to generateStructure() 然后generateStructure()遍历所有记录,并查找传递给generateStructure()的id为parent_id的记录
  5. Once the current category has been added to the structure, generateStructure() will then call the method countChildren() . 将当前类别添加到结构后, generateStructure()将调用方法countChildren() If countChildren() returns an int greater than 0, the current record has children, so we generate another menu element 如果countChildren()返回的int大于0,则当前记录有子级,因此我们生成另一个菜单元素
  6. generateStructure() then returns the generated HTML generateStructure()然后返回生成的HTML

I haven't debugged the above code, there may be a few syntax errors. 我尚未调试上面的代码,可能有一些语法错误。 But, it should output html similar to this: 但是,它应该输出类似于以下内容的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