如何使用php为foreach中的每三个结果添加html元素


how to add html element for every three result in foreach using php?

我想使用php为foreach中的每3个结果添加ul-li-html元素。我试过以下方法。但我没有得到确切的结果。请告知这个

 Array ( [0] => stdClass Object ( [category_name] => Architect ) 
 [1] => stdClass Object ( [category_name] => Doors & Windows ) 
 [2] => stdClass Object ( [category_name] => Garage Doors ) 
 [3] => stdClass Object ( [category_name] => Home Inspection ) )

      <?php 
                    $i=0;
                     //$arrays = array_chunk($get_business_cat_details, 3);
                    foreach($get_business_cat_details as $key=> $cat_name){                                                         
                                //echo " <ul style='margin-top: 20px;'><li><a href='#'>".ucwords($cat_name->category_name) ."</a></li>";
                                if($i%3==0){
                                    echo "<ul><li><a href='#'>".ucwords($cat_name->category_name) ."</a></li></ul>";
                                }else{
                                    echo "<ul><li><a href='#'>".ucwords($cat_name->category_name) ."</a></li></ul>";
                                }
                                $i++;
                        }

                    ?>

输出:

 Power -- Wash --  Cleaning Paint 
East Valley --  Central/South Phx --  West Valley 

请尝试以下代码。

    <?php
$i = 0;
//$arrays = array_chunk($get_business_cat_details, 3);
foreach ($get_business_cat_details as $key => $cat_name) {
    //echo " <ul style='margin-top: 20px;'><li><a href='#'>".ucwords($cat_name->category_name) ."</a></li>";
    if($i==0) {
        $get_style="style='margin-top: 20px;'";
    } else {
        $get_style="";
    }
    if ($i % 3 == 0) {
        echo "<ul ".$get_style." >";
    }
    echo "<li><a href='#'>" . ucwords($cat_name->category_name) . "</a></li>";
    $i++;
    if ($i % 3 == 0 && $i != 0) {
        echo "</ul>";
    }
}
?>

我认为这可能是您想要的。由于您的初始标记在循环中,所以每个结果基本上都是一个完整的列表。通过从循环中移除,您可以关闭标记并在循环中动态打开一个新标记。

    <? php
    $i = 0;
  echo "<ul>";
   foreach($get_business_cat_details as $key => $cat_name) {
     if ($i % 3 == 0) {
       echo "</ul><ul>";
     }
     echo "<li><a href='#'>".ucwords($cat_name - > category_name).
       "</a></li>";
     $i++;
   }
echo "</ul>";
    ?>