I have an array containing a "Variable" amount of results/entries.
I use foreach as normal to echo the array results.
Problem: I want to wrap every 5 results from th开发者_开发问答e array in Unordered list.
I do not know the total number of results since it's variable. So for example if it contains 18 items. It should display 4 ULs, the first 3 ULs containing 5 results and the last UL contains only the remaining 3 items.
Is that simple to do? Thanks very much in advance for your help. :)
I rarely used this function, but array_chunk seems to do what you want.
$chunks = array_chunk($original, 5);
foreach ($chunks as $each_chunk) {
// echo out as unordered list
}
This is a fairly straightforward algorithm:
$htmlOutput = "";
for($i=0;$i<count($myArray);$i++)
{
if($i%5==0)
{
$htmlOutput.= "<ul>";
}
$htmlOutput.= "<li>".$myArray[$i]."</li>";
if($i%5==4)
{
$htmlOutput.= "</ul>";
}
}
if(count($myArray)%5!=0)
{
$htmlOutput.= "</ul>";
}
echo $htmlOutput;
You may need to modify this a bit to suit your requirements
$cnt = 1;
foreach ($arr as $key => $val)
{
if($cnt==1) echo "<ul>";
echo "<li>$val</li>";
$cnt++;
if($cnt==5)
{
echo "</ul>";
$cnt=1;
}
}
How about this:
<?php
$num_per_list = 5; // change me
$dudes = array("bill","jim","steve","bob","jason","brian","dave","joe","jeff","scott");
$count = 0;
$list_items = "";
foreach($dudes as $dude) {
$break = (($count%$num_per_list) == ($num_per_list-1));
$list_items .= "<li>" . $dude . "</li>";
if(($break) || (count($dudes)==($count+1))) {
$output = "<ul>" . $list_items . "</ul>";
$list_items = "";
// Output html
echo $output;
}
$count++;
}
?>
Let's suppose you put the list in an array...
$count = 0;
foreach ($unorderedList as $item) {
$count = ($count + 1)%5;
if ($count == 0) {
// wrap here
}
...do the stuff for every item you need
}
精彩评论