Build recursive nested menu from array

后端 未结 3 1789
野性不改
野性不改 2021-01-23 03:09

I\'m trying to build a recursive menu which would look something like this when finished, with an infinite amount of nested items:



        
3条回答
  •  情书的邮戳
    2021-01-23 04:01

    Suppose that after extracting all menu items from the database, it outputs an output as follows.

    $items = [
    [
        'id' => '1',
        'parent_id' => '0',
        'title' => 'Menu 1',
    ],
    [
        'id' => '2',
        'parent_id' => '0',
        'title' => 'Menu 2',
    ],
    [
        'id' => '3',
        'parent_id' => '2',
        'title' => 'Menu 2 1',
    ],
    [
        'id' => '4',
        'parent_id' => '0',
        'title' => 'Menu 3',
    ],
    [
        'id' => '5',
        'parent_id' => '4',
        'title' => 'Menu 3 1',
    ],
    [
        'id' => '6',
        'parent_id' => '5',
        'title' => 'Menu 3 1 1',
    ],
    [
        'id' => '7',
        'parent_id' => '5',
        'title' => 'Menu 3 1 2',
    ],
    [
        'id' => '8',
        'parent_id' => '7',
        'title' => 'Menu 3 1 2 1',
    ],
    [
        'id' => '9',
        'parent_id' => '4',
        'title' => 'Menu 3 2',
    ],
    [
        'id' => '10',
        'parent_id' => '0',
        'title' => 'Menu 4',
    ]];
    

    Let's write a function to process the data in Array format and return html

    /**
     * Recursive and prints the elements of the given parent id.
     * @param $items
     * @param string $parentId
     */
    function buildNestedItems($items, $parentId = "0", $wrapperTag = 'ul', $itemTag = 'li')
    {
        // Parent items control
        $isParentItem = false;
        foreach ($items as $item) {
            if ($item['parent_id'] === $parentId) {
                $isParentItem = true;
                break;
            }
        }
    
        // Prepare items
        $html = "";
        if ($isParentItem) {
            $html .= "<$wrapperTag>";
            foreach ($items as $item) {
                if ($item['parent_id'] === $parentId) {
                    $html .= "<$itemTag>" . $item['title'] . "";
                    $html .= buildNestedItems($items, $item['id']);
                }
            }
            $html .= "";
        }
        return $html;
    }
    

    Let's print the prepared html i page

    
    

提交回复
热议问题