简体   繁体   中英

PHP foreach loop on unknown depth multidimensional array

I have a multidimensional array consisting of a directory structure or a tree if you want, but how can I loop through this data when I don't know the depth of the array? Here is an example of how the array could look like

在此处输入图片说明

I want to go through each item here so that I can add the items to <ul> and <li> to get a "menu" kind off. Just like an file-explorer.

Tried using foreach but that is kinda hard when you don't always know the depth of the array.

Create a recursive function that checks if the element is an array, then if it is - call the function again, otherwise create the list-item as normal.

function my_print($array) {
    $output = "<ul>";
    foreach ($array as $value) {
        if (is_array($value)) {
            $output .= "<li>".my_print($value)."</li>";
        } else {
            $output .= "<li>".$value."</li>";
        }
    }
    $output .= "</ul>";
    return $output;
}

With an array as

$array = ['value', 'value',
            ['array 1', 'array 1', 
                ['array 2']],
                ['array with more depth', 
                    ['array deep',
                        ['array deeper']]]
        ];

..the output will be (although not formatted - formatted here for visual comparing with the array),

<ul>
    <li>value</li>
    <li>value</li>
    <li>
        <ul>
            <li>array 1</li>
            <li>array 1</li>
            <li>
                <ul>
                    <li>array 2</li>
                </ul>
            </li>
        </ul>
    </li>
    <li>
        <ul>
            <li>array with more depth</li>
            <li>
                <ul>
                    <li>array deep</li>
                    <li>
                        <ul>
                            <li>array deeper</li>
                        </ul>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM