1

I can't figure out how to group my subcategories into a container after every fifth record.

for example I would like to output my subcats like this

<ul>
<li>
 Main category
 <div>
  <div class="subcontainer">
   sub1
   sub2
   sub3
   sub4
   sub5
  </div>
  <div class="subcontainer">
   sub6
   sub7
   sub8
   sub9
   sub10
  </div>
 </div>
</li>
</ul>

I tried this:

<?php
$i=0;
foreach ($cat->sub as $child) {
  if($i % 5 == 0){
   echo '<div class="subcontainer"><div>'.$child->name.'</div></div>';
  } $i++;
}
?>

But this will output only the 5th elements in the array.

4

2 回答 2

5

您需要始终打印您的$child->name变量,并且每隔 5 项也打印该</div><div>部分。你几乎拥有它。

$i=0;
echo '<div class="subcontainer">';
foreach($cat->sub as $child) {
    $i++;
    echo $child->name; // I'm assuming this is what contains your "sub1"-"sub10"
    if ($i % 5 == 0) {
        echo '</div><div class="subcontainer">';
    }
}
echo '</div>';
于 2012-07-26T15:11:47.303 回答
0

你也可以$i得到foreach ($cat->sub as $i=>$child)

于 2012-07-26T15:15:48.460 回答