PHP / HTML - Generate a html list from a array
I have a array like ('mary', 'johnny', 'butch', 'pony', 'katy', 'chuck', 'norris')
The number of elements can vary...
How can I build a nice list from all these elements, like this:
<ul>
<li>
Mary
Johnny
Butch
</li>
<li>
Pony
Katy
</li>
<li>
Chu开发者_Python百科ck
Norris
</li>
?
Basically build the list like a spiral:
> -------------
|
<--------------
|
>--------------
|
<--------------
The number of list items is fixed, for eg. 3 in the example above
Yet Another Path, Because There Was Not Weird Enough Code Posted.
//set the amount of items
$li_items = 3;//can be anything, really
echo '<ul>';
//loop
for(;$li_items > 0;$li_items--){
echo "\n\t<li>\n\t".implode("\n\t",
array_splice($array,0,ceil(count($array)/$li_items))
)."\n\t<li>";
}
echo '</ul>';
You want to group them in 3's? Something like:
<?php
$list = ('mary', 'johnny', 'butch', 'pony', 'katy', 'chuck', 'norris');
$c = 0;
$LIMIT = 3;
echo "<ul>";
foreach($list as $current) {
echo "<li>$current</li>";
$c += 1;
if($c == $LIMIT) { echo "</ul><ul>"; }
}
echo "</ul>";
Very ugly, but gets the job done
What you should do is separate presentation from logic. Instead of figuring out how many items should go in each element, put each item in it's own element. Each one is a line-item after all.
<ul class="the_list">
<li>Mary</li>
<li>Johnny</li>
<li>Butch</li>
<li>Pony</li>
<li>Katy</li>
<li>Chuck</li>
<li>Norris</li>
</ul>
Then use CSS to display the list however you want. For example, you could do something like this:
.the_list { width:300px;}
.the_list li { display:block;float:left;width:100px;}
You'll need some additional rules like a reset stylesheet first, but that's the gist of it.
You could loop through the array and use modulus
for ($i = 0; $i < count($array); $i++)
{
if ($i % 3 == 0)
{
//append to first li
}
else if ($i % 3 == 1)
{
//append to second li
}
else
{
//append to third li
}
}
精彩评论