Search code examples
phparraysarray-filter

Filter array for creating menu sub menu in php


My existing array like this

$menus = array(
        0 =>array(
                "id"=> 1,
                "name"=> "A",
                "parent_id"=> 0
            ),
         1 =>array(
                "id"=> 2,
                "name"=> "B",
                "parent_id"=> 1
            ),
         2 =>array(
                "id"=> 3,
                "name"=> "C",
                "parent_id"=> 1
            ),
         3 =>array(
                "id"=> 4,
                "name"=> "D",
                "parent_id"=> 2
            ),
        4 =>array(
                "id"=> 5,
                "name"=> "E",
                "parent_id"=> 0
            ),

     );

I want to create that array like below output.

Expected Array

Array
(
    [0] => Array
        (
            [Menu] => Array
                (
                   [0] => Array
                          ( [name] => A
                            [Sub_menu] => Array
                             (
                                  [0] => Array
                                      (
                                        [name] => B
                                      ),
                                  [1] => Array
                                     (
                                        [name] => C
                                        [Sub_menu] => Array
                                          (
                                              [0] => Array
                                              (
                                                [name] => D
                                              ),

                                          )
                                     )
                             )
                          ),
                   [1] => Array
                          ( [name] => E

                          )
                )
         )
)

I tried some code and those are not working . my work output was like this image enter image description here

which repeating again in foreach loop in menu.


Solution

  • You can use this function to construct menu recursively.

    function makeMenu($items, $parentId)
    {
        $menu = array_filter($items, function ($item) use ($parentId) {
            return $item['parent_id'] == $parentId;
        });
        foreach ($menu as &$item) {
            $subItems = makeMenu($items, $item['id']);
            if (!empty($subItems)) {
                $item['sub_menu'] = $subItems;
            }
        }
        return $menu;
    }
    

    Call it with $parentId = 0 and it will do work.

    $readyMenu = makeMenu($itemsArray, 0);