Build nested UL and LI from linear array
Posted: Thu Dec 10, 2009 9:35 pm
For the last week I have struggled with this, although I eventually realized it might be possible using a linear array, this is that attempt:
Whats weird is the output actually renders the structure properly, at least in IE but it's not valid code and it's mission critical this code be valid XHTML.
The idea is simple enough , I have an array such like:
This array would output something like:
A few assumptions can be made...the array which is to be rendered will always have itès parents come first, as the array is built using recursion, so you would never have an instance like the above but in the order like:
Forcing you into keeping track of which depth you are at and having to revert back to that nest level to add a record found at the end of the array. Parent items (whose depth is less than children) are always going to come first, by design.
Anyways, Ive had it with this this problem...Iève spent to much time in the lofty heavens thinking about abstractions, architecture, etc...now my brain will not comprehend low-level implementation details, anything beyond tying to gather interfaces, etc.
Ièm actually implementing my 2nd (or 7th) attempt but still curious to see if anyone can come up with something more clever or efficient.
Please no recursion or conversion of the linear array to a structured array, then converting the nested array into this XHTML markup...this might be a last resort technique, so unless you really have to, Ièm still interested in seeing how you might convert a linear array into something nested.
Cheers,
Alex
Code: Select all
$depth = 0;
foreach($this->items as $item){
if($item['depth'] > $depth){
echo '<ul>';
}
else{
echo '</ul>';
}
echo '<li>';
echo $item['label'];
echo '</li>';
//if($item['depth'] < $depth){
// echo '</ul>';
//}
$depth = $item['depth'];
}The idea is simple enough , I have an array such like:
Code: Select all
name, label, depth
------------------
Alex, Manager, 0
Sean, Contractor, 1
Mike, Contractor, 1
Sara, Specialist, 2
John, Developer, 0Code: Select all
Alex
Sean
Mike
Sara
JohnCode: Select all
name, label, depth
------------------
Alex, Manager, 0
Sara, Specialist, 2
John, Developer, 0
Sean, Contractor, 1
Mike, Contractor, 1
Anyways, Ive had it with this this problem...Iève spent to much time in the lofty heavens thinking about abstractions, architecture, etc...now my brain will not comprehend low-level implementation details, anything beyond tying to gather interfaces, etc.
Ièm actually implementing my 2nd (or 7th) attempt but still curious to see if anyone can come up with something more clever or efficient.
Please no recursion or conversion of the linear array to a structured array, then converting the nested array into this XHTML markup...this might be a last resort technique, so unless you really have to, Ièm still interested in seeing how you might convert a linear array into something nested.
Cheers,
Alex