[英]Getting results from a PHP array: How can I wrap every 5 results in Unordered List?
我有一個數組,其中包含“結果” /條目的“變量”數量。
我通常使用foreach來回顯數組結果。
問題:我想將數組的每5個結果包裝在無序列表中。
我不知道結果的總數,因為它是可變的。 因此,例如,如果它包含18個項目。 它應顯示4個UL,前三個UL包含5個結果,最后一個UL僅包含其余3個項目。
這樣簡單嗎? 非常感謝您的幫助。 :)
我很少使用此函數,但array_chunk似乎可以滿足您的要求。
$chunks = array_chunk($original, 5);
foreach ($chunks as $each_chunk) {
// echo out as unordered list
}
這是一個相當簡單的算法:
$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;
假設您將列表放在數組中...
$count = 0;
foreach ($unorderedList as $item) {
$count = ($count + 1)%5;
if ($count == 0) {
// wrap here
}
...do the stuff for every item you need
}
您可能需要對此進行一些修改以適合您的要求
$cnt = 1;
foreach ($arr as $key => $val)
{
if($cnt==1) echo "<ul>";
echo "<li>$val</li>";
$cnt++;
if($cnt==5)
{
echo "</ul>";
$cnt=1;
}
}
這個怎么樣:
<?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++;
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.