I have the following array which I want to transform into an unordered list (HTML).
Array
(
[0] => Array
(
[url] => /
[id] => 53a8717fe9ab5
[template] => home
[title] => Home
)
[1] => Array
(
[url] => /about
[id] => 53a871fe8b05b
[template] => content
[title] => About
)
[2] => Array
(
[url] => /about/sub
[id] => 53cb88b7ed22d
[template] => content
[title] => About (sub)
)
[3] => Array
(
[url] => /about/sub/subsub
[id] => 53cb88bc7d32d
[template] => content
[title] => About (subsub)
)
[4] => Array
(
[url] => /contact
[id] => 53a8718981161
[template] => content
[title] => Contact us
)
)
So I'm trying to create a multidimensional array from the one above which looks like this:
Array
(
[0] => /
[1] => /about
[about] => Array
(
[0] => /about/sub
[sub] => Array
(
[0] => /about/sub/subsub
)
)
[2] => /contact
)
But that's as far as I'm getting... Let alone the creation of the actual <ul>
.
Any help would be very much appreciated.
EDIT
I generated the recursive <ul>
using:
private function generateTree($from) {
$to = [];
foreach ( $from as $element ) {
$path = explode('/', $element["url"]);
if ( count($path) === 1 ) array_unshift($path, '/');
$_to = &$to;
for ( $i = 0; $i < count($path)-1; $i++ ) {
if ( !array_key_exists($path[$i], $_to) ) $_to[$path[$i]] = [];
$_to = &$_to[$path[$i]];
print_r ( implode("/", $path));
echo "<br>";
}
$_to[] = $element["url"];
}
return $to[""];
}
And this is my expected output:
<ul>
<li><a href="/">Home</a></li>
<li>
<a href="/about">About</a>
<ul>
<li>
<a href="/about/sub">About (sub)</a>
<ul>
<li><a href="/about/sub/subsub">About (subsub)</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="/contact">Contact</a></li>
</ul>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…