Search code examples
phpmultidimensional-arraylevels

Know the element level in multidimensional array


Well, I am here again dealing with arrays in php. I need your hand to guide me in the right direction. Suppose the following array:

-fruits
    --green
        ---limon
        ---mango
    --red
        ---apple


-cars
    --ferrari
        ---enzo
            ----blue
            ----black
        ---318
    --lamborg
        ---spider
        ---gallardo
            ----gallado-96
                -----blue
                -----red
            -----gallado-98

The - (hyphen) symbol only illustrates the deep level.

Well, I need to build another array (or whatever), because it should be printed as an HTML select as below:

-fruits
--green
---limon
---mango
--red
---apple
-cars
--ferrari
---enzo
----blue
----black
---318
--lamborg
---spider
---gallardo
----gallado-96
-----blue
-----red
-----gallado-98

Looks that for each level element, it should add a space, or hyphen to determinate that it belongs to a particular parent.

EDIT

The have provide an answer provideng my final code. The html select element will display each level as string (repeating the "-" at the begging of the text instead multi-level elements.


Solution

  • Here's a simple recursive function to build a select dropdown given an array. Unfortunately I'm not able to test it, but let me know if it works. Usage would be as follows:

    function generateDropdown($array, $level = 1)
    {
        if ($level == 1)
        {
            $menu = '<select>';
        }
        foreach ($array as $a)
        {
            if (is_array($a))
            {
                $menu .= generateDropdown($a, $level+1);
            }
            else
            {
                $menu .= '<option>'.str_pad('',$level,'-').$a.'</option>'."\n";
            }
        }
        if ($level == 1)
        {
            $menu = '</select>';
        }
        return $menu;
    }