Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Edit:</strong></p> <p>Changed to cater for updated question.</p> <p>I'm using an array index of <code>__title</code> to hold the page title. As long as you never have a directory in your tree called <code>__title</code> this should be fine. You're free to change this sentinel value to anything you wish however.</p> <p>I have also changed it so the list building function returns a string, so that you can store the value for use later in your page. (You can of course just do <code>echo build_list(build_tree($paths))</code> to output the list directly.</p> <pre><code>&lt;?php $paths = array( 'about/contact/' =&gt; 'Contact Us', 'about/contact/form/' =&gt; 'Contact Form', 'about/history/' =&gt; 'Our History', 'about/staff/' =&gt; 'Our Staff', 'about/staff/bobjones/' =&gt; 'Bob', 'about/staff/sallymae/' =&gt; 'Sally', 'products/' =&gt; 'All Products', 'products/gifts/' =&gt; 'Gift Ideas!', 'products/widgets/' =&gt; 'Widgets' ); function build_tree($path_list) { $path_tree = array(); foreach ($path_list as $path =&gt; $title) { $list = explode('/', trim($path, '/')); $last_dir = &amp;$path_tree; foreach ($list as $dir) { $last_dir =&amp; $last_dir[$dir]; } $last_dir['__title'] = $title; } return $path_tree; } function build_list($tree, $prefix = '') { $ul = ''; foreach ($tree as $key =&gt; $value) { $li = ''; if (is_array($value)) { if (array_key_exists('__title', $value)) { $li .= "$prefix$key/ &lt;a href=\"/$prefix$key/\"&gt;${value['__title']}&lt;/a&gt;"; } else { $li .= "$prefix$key/"; } $li .= build_list($value, "$prefix$key/"); $ul .= strlen($li) ? "&lt;li&gt;$li&lt;/li&gt;" : ''; } } return strlen($ul) ? "&lt;ul&gt;$ul&lt;/ul&gt;" : ''; } $tree = build_tree($paths); $list = build_list($tree); echo $list; ?&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload