如何在 foreach 循环期间构建 HTML 以包含输出


How to build HTML to contain the output during a foreach loop

我有一个 foreach 循环,我需要修改它,以便在计数为 10 后关闭它循环的 html 结构并打开一个新结构以添加 10 个计数,依此类推,直到数组中没有更多元素。

<?php
// open the ul
$location_lists .= '<ul';
// get the array
$locations = get_posts(array(
'post_type' => 'location',
'showposts' => -1
));
foreach ($locations as $location) {
  $address = some code here;      
  $location_lists .= '<li>';
  $location_lists .= '<span>'. ($address) .'</span>';
  $location_lists .= '</li>';
};
// after 10 loops close the ul
$location_lists .= '</ul>';
// open a new ul to hold 10 more li's etc...
$location_lists .= '<ul';
?>

因此,如果数组中有 24 个元素,我需要 2 个 ul,每个包含 10 个 li,第 3 个 ul 将包含剩余的 4 个 li。

$location_lists .= '<ul>';
$i=0;
foreach ($locations as $location) {
  $i++;
  $address = some code here;    
  $location_lists .= '<li>';
  $location_lists .= '<span>'. ($address) .'</span>';
  $location_lists .= '</li>';
  if (($i % 10) == 0) {
       $location_lists .= '</ul><ul>';
  }
};
$location_lists .= '</ul>';
    $location_lists='';
$locations = get_posts(array(
'post_type' => 'location',
'showposts' => -1
));
$i=0;
foreach ($locations as $location) {
  if($i==0){$location_lists .= '<ul>';}
  $address = some code here;      
  $location_lists .= '<li>';
  $location_lists .= '<span>'. ($address) .'</span>';
  $location_lists .= '</li>';
  $i++;
 if($i==10){$location_lists .= '</ul>';$i=0}
};
if($i!=0){$location_lists .= '</ul>';}