Category Hierarchy (PHP/MySQL)

后端 未结 5 1457
悲&欢浪女
悲&欢浪女 2020-11-29 20:57

I am trying to get my all categories and sub-categories from MySQL database in a hierarchy:

My result should be like that (just example):

5条回答
  •  醉话见心
    2020-11-29 21:47

    When using an adjacency list model, you can generate the structure in one pass.

    Taken from One Pass Parent-Child Array Structure (Sep 2007; by Nate Weiner):

    $refs = array();
    $list = array();
    
    $sql = "SELECT item_id, parent_id, name FROM items ORDER BY name";
    
    /** @var $pdo \PDO */
    $result = $pdo->query($sql);
    
    foreach ($result as $row)
    {
        $ref = & $refs[$row['item_id']];
    
        $ref['parent_id'] = $row['parent_id'];
        $ref['name']      = $row['name'];
    
        if ($row['parent_id'] == 0)
        {
            $list[$row['item_id']] = & $ref;
        }
        else
        {
            $refs[$row['parent_id']]['children'][$row['item_id']] = & $ref;
        }
    }
    

    From the linked article, here's a snippet to create a list for output. It is recursive, if there a children for a node, it calls itself again to build up the subtree.

    function toUL(array $array)
    {
        $html = '
      ' . PHP_EOL; foreach ($array as $value) { $html .= '
    • ' . $value['name']; if (!empty($value['children'])) { $html .= toUL($value['children']); } $html .= '
    • ' . PHP_EOL; } $html .= '
    ' . PHP_EOL; return $html; }

    Related Question:

    • How to obtain a nested HTML list from object's array recordset?

提交回复
热议问题