Reputation: 235
I would like to add ul li html element for every 3 results in foreach using php. I have tried with the following method. but i am not getting the exact results. please advise on this
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++;
}
?>
Output:
Power -- Wash -- Cleaning Paint
East Valley -- Central/South Phx -- West Valley
Upvotes: 1
Views: 78
Reputation: 720
Please try below code.
<?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>";
}
}
?>
Upvotes: 1
Reputation: 1156
I think this may be what your looking for. Since your initial tag is in your loop every result would essentially be a complete list. By removing the from the loop you can close the tag and open a new one dynamically in the loop.
<? 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>";
?>
Upvotes: 0