简体   繁体   English

从PHP数组获取结果:如何将每5个结果包装在无序列表中?

[英]Getting results from a PHP array: How can I wrap every 5 results in Unordered List?

I have an array containing a "Variable" amount of results/entries. 我有一个数组,其中包含“结果” /条目的“变量”数量。

I use foreach as normal to echo the array results. 我通常使用foreach来回显数组结果。

Problem: I want to wrap every 5 results from the array in Unordered list. 问题:我想将数组的每5个结果包装在无序列表中。

I do not know the total number of results since it's variable. 我不知道结果的总数,因为它是可变的。 So for example if it contains 18 items. 因此,例如,如果它包含18个项目。 It should display 4 ULs, the first 3 ULs containing 5 results and the last UL contains only the remaining 3 items. 它应显示4个UL,前三个UL包含5个结果,最后一个UL仅包含其余3个项目。

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. 我很少使用此函数,但array_chunk似乎可以满足您的要求。

$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;

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
}

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++;
}

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM