Adding a class name to every fouth item in a forloop - php

I'm used to doing this with Django and it's fairly simple, so trying to workout how it's done in PHP. What I'd like to do is within a PHP for foreach loop I would like to add the class name of 'last' to every fourth item in the list.
PHP code:
<?php
$products = array();
$product_counter = 0;
foreach ($_productCollection as $_product)
{
?>
So this is my current HTML output:
<li>
<div class="contentWrap"> content here </div>
</li>
<li>
<div class="contentWrap"> content here </div>
</li>
<li>
<div class="contentWrap"> content here </div>
</li>
<li>
<div class="contentWrap"> content here </div>
</li>
However, what I would like to acheive is:
<li>
<div class="contentWrap"> content here </div>
</li>
<li>
<div class="contentWrap"> content here </div>
</li>
<li>
<div class="contentWrap"> content here </div>
</li>
<li>
<div class="contentWrap last"> content here </div>
</li>
I was using the nth child attribute in CSS3 but it needs to be supported in IE8!
Anyway, PHP isn't my strong point and can't make use of the examples i've found online so any help would be much appreciated.
Thanks

Use something like this:
$counter = 0;
foreach ($_productCollection as $_product) {
//whatever
if ($counter % 4 == 3) {
//do stuff for every 4th element
}
$counter++;
}

Simple right?
for($i = 0; $i < $countOfArray; $i++) {
if($i % 4 == 3) {
// add last class ....
}
}

Related

Count a foreach loop and create new element in php

I'm working on a Mega Menu for WooCommerce Product Category. I'm able to get the list of all Subcategories using the code below;
$parent_id = 37; //ID of the Parent Category
$subCat_of_parent = get_terms('product_cat',array('child_of' => $parent_id));
Then used in a html structure as below;
<div class="row">
<div class="col-md-6">
<ul>
<?php
foreach ($subCat_of_parent as $subcat) {
?>
<li>
<?php echo $subcat->name; ?>
</li>
<?php
}
?>
</ul>
</div>
</div>
This worked by getting all the list of subcategory of the parent category in this format;
<div class="row">
<div class="col-md-6">
<ul>
<li><a>1st subcategory</a></li>
<li><a>2nd subcategory</a></li>
<li><a>3rd subcategory</a></li>
<li><a>4th subcategory</a></li>
<li><a>5th subcategory</a></li>
<li><a>6th subcategory</a></li>
</ul>
<div>
</div>
what i want to achieve is after the 3rd subcategory, it should break and continue on a new column, so that i can get something like this;
<div class="row">
<div class="col-md-6">
<ul>
<li><a>1st subcategory</a></li>
<li><a>2nd subcategory</a></li>
<li><a>3rd subcategory</a></li>
</ul>
<div>
<div class="col-md-6">
<ul>
<li><a>4th subcategory</a></li>
<li><a>5th subcategory</a></li>
<li><a>6th subcategory</a></li>
</ul>
<div>
</div>
How can i achieve this? Thanks for your help in advance
You can use array_chunk() to divide the array into groups of 3.
<div class="row">
<?php
$chunks = array_chunk($subCat_of_parent, 3);
foreach ($chunks as $group) {
print '<div class="col-md-6">';
print '<ul>';
foreach ($group as $subcat) {
print '<li>';
//to-do
print '</li>';
}
print '</ul>';
print '</div>';
}
?>
</div>
You need to emit the inner <div class="col-md-6"><ul> and the </ul></div> part every three categories.
Here is the pseudocode:
Emit <div class="row">
Set a counter, something like $i = 0
Start your for loop, foreach ($subCat_of_parent as $subcat) {
Now say if ($i == 0), emit the start div tag and start ul tag.
Emit your list item
$i = ($i + 1) % 3
Now say if ($i == 0), emit the close ul tag and close div tag.
If the number of subcategories is not a multiple of three, you need extra logic at the end to make sure the last group is properly closed off.
<?php
$arr = array(1, 2, 3, 4,5,6);
$count = 0;
?>
<div class="row">
<?php
foreach ($subCat_of_parent as $subcat)
{
// echo "count =".$count;
if($count%3 == 0)
{
echo ('<div class="col-md-6">
<ul>');
}
$count++;
?>
<li>
<?php echo $subcat->name; ?>
</li>
<?php
if($count%3 == 0)
{
echo ('
</ul></div>');
}
}
?>
</div>
Below code is working, You can use this.
<?php
$subCat_of_parent = array('1st sub', '2nd sub', '3rd sub', '4th sub', '5 sub', '6 sub', '7 sub');
$subCat_of_parent = array_chunk($subCat_of_parent, 3);
?>
<div class="row">
<?php
foreach ($subCat_of_parent as $subcats) {
?>
<div class="col-md-6">
<ul>
<?php
foreach ($subcats as $subcat) {
?>
<li><?php echo $subcat; ?></li>
<?php
}
?>
</ul>
</div>
<?php
}
?>
</div>

Dynamically give list items <li> a unique class with PHP

I am dynamically populating a list based on what is in the database, and I would like each list item to have a unique class name - something simple, for example the first would have the class item-1, and the second would have the class item-2.
This is the php code I am using to create the list:
<?php
$metas=trim(get_post_meta($post->ID,'hike_meta',true),'');
$metas_arr=explode("\n",$metas);
$metas1=array_slice($metas_arr,0,3);
$metas2=array_slice($metas_arr,3,3);
?>
<div class="loca_meta">
<ul>
<?php foreach($metas1 as $meta){
list($k, $v) = explode('|', $meta);
echo "<li><span class='bold'>$k</span>:<br>$v</li>";
}?>
</ul>
</div>
<div class="loca_meta">
<ul>
<?php foreach($metas2 as $meta){
list($k, $v) = explode('|', $meta);
echo "<li><span class='bold'>$k</span>:<br>$v</li>";
}?>
</ul>
</div>
What extra code do I need, to give each list item a unique class? As a side note, I am very much a beginner when it comes to php, so please let me know if you need any more information.
You can add $counter variable to get the incremented value and assign it to class.
<div class="loca_meta">
<ul>
<?php $counter = 0; foreach($metas1 as $meta){
list($k, $v) = explode('|', $meta);
echo "<li><span class='bold <?php echo "item_".$counter ?>'>$k</span>:<br>$v</li>";
$counter++;
}?>
</ul>
</div>
<div class="loca_meta">
<ul>
<?php foreach($metas2 as $meta){
list($k, $v) = explode('|', $meta);
echo "<li><span class='bold <?php echo "item_".$counter ?>'>$k</span>:<br>$v</li>";
$counter++;
}?>
</ul>
</div>
You can use for loop:
<?php for($i = 0; $i < count($metas1); $i++){
list($k, $v) = explode('|', $metas[$i]);
echo "<li><span class="bold item-".$i+1.">$k</span>:<br>$v</li>";
}?>
Result will be:
<li><span class="bold item-1"><!-- content --></span>:<br><!-- content --></li>
<li><span class="bold item-2"><!-- content --></span>:<br><!-- content --></li>
<li><span class="bold item-3"><!-- content --></span>:<br><!-- content --></li>
and so on.

PHP: split a mySQLi array in two divs?

I'm currently working on a page that calls a mySQL database to populate a list of members. However, I need that list to be split into two equal parts, so that half can float to the left and half to the right. However, I have beat this horse to death and still cannot figure out how to split the array.
Here's what I have currently:
<div class="holder">
<?php
$members = $db->query('SELECT * FROM tableContacts ORDER BY lastName ASC');
$rowcount = mysqli_num_rows($members);
if ( $rowcount > 0 ) { ?>
<div class="members-left">
<ul class="members">
<?php while ($row = $members->fetch_assoc()) { ?>
<li class="member">
//SOME CONTENT HERE
</li>
<?php } ?>
</ul>
</div>
<?php } ?>
</div>
However, I want the output to look something like this (let's say my table has 10 members):
<div class="holder">
<!--output first half of members from table: -->
<div class="members-left">
<ul class="members">
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
</ul>
</div>
<!--output second half of members from table: -->
<div class="members-right">
<ul class="members">
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
</ul>
</div>
</div>
I've tried setting counters and using things like if($i <= $rowcount/2), but to no avail. Any help would be greatly appreciated—I'm very new to mySQL and have limited knowledge of PHP, so this one has me stumped.
add a control variable like "$i". add +1 to $i every loop. and check if $i reached half of number of rows. if reached close ul and div and open new div and ul and set $i to 0
<div class="holder">
<?php
$members = $db->query('SELECT * FROM tableContacts ORDER BY lastName ASC');
$rowcount = mysqli_num_rows($members);
$i=0;
if ( $rowcount > 0 ) { ?>
<div class="members-right">
<ul class="members">
<?php while ($row = $members->fetch_assoc()) { ?>
<li class="member">
//SOME CONTENT HERE
</li>
<?php
$i++;
if($i>=($rowcount/2)){
echo '</ul></div>
<div class="members-right">
<ul class="members">';
$i=0;
}
} ?>
</ul>
</div>
<?php } ?>
</div>
You could use a for loop for the first half and just finish the second half with a while loop that goes until there are no more results.
First half:
for($i = 0; $i <= $rowcount/2 && $row = $members->fetch_assoc(); $i++)
Second half
while ($row = $members->fetch_assoc())
Example with HTML
<div class="members-left">
<ul class="members">
<?php for($i = 0; $i <= $rowcount/2 && $row = $members->fetch_assoc(); $i++) { ?>
<li class="member">
// do something with $row
</li>
<?php } ?>
</ul>
</div>
<div class="members-right">
<ul class="members">
<?php while ($row = $members->fetch_assoc()) { ?>
<li class="member">
// do something with $row
</li>
<?php } ?>
</ul>
</div>
I would recommend you to make 2 arrays of your members and then print them out. The advantage is you will have more control of the members and your code will be more readable for later use;
<?php
$i =0;
while ($row = $members->fetch_assoc()) {
if($i % 2 == 0)
{
$right_members[] = $row;
}
else
{
$left_members[] = $row;
$i++;
}
echo '
<div class="members-right">
<ul class="members">';
foreach($right members as $r_member){
echo '<li class="member">...</li>';
}
echo '
</ul>
</div>';
//SAME WITH LEFT MEMBERS
?>
Having a counter was an idea, I will not debate on having model logic in view ;)
well, a solution would be :
<div class="holder">
<div class="members-column">
<ul class="members">
<?php
$members = $db->query('SELECT * FROM tableContacts ORDER BY lastName ASC');
$rowcount = mysqli_num_rows($members);
$i = 0;
while ($row = $members->fetch_assoc()) {
?>
<li class="member">
//SOME CONTENT HERE
</li>
<?
// Check if current row is the 'middle count', creating a new column
if ($i === ceil($rowcount / 2)) : ?>
</ul>
</div>
<div class="members-column">
<ul class="members">
<?php endif; ?>
<?php
$i++;
}
?>
</ul>
</div>
</div>

displaying images from mysql in php in rows and cols

i need to display images from mysql in my gallery. i have a responsive template. i have around 40 images in my mysql i want to fetch images and display it in gallery view of 4 column per row and it should go to the next set
here is my code for the html gallery
<ul class="row box2">
<li class="span4">
<img></img>
</li>
<li class="span4">
<img></img>
</li>
<li class="span4">
<img></img>
</li>
<li class="span4">
<img></img>
</li>
</ul>
so above is my code i need to repeat this code for every 4 image i show from Mysql using php so that i can form a gallery
pls help in looping this for every four image fetched so that i disaplay all my 40 images in 10 rows 4 per column
thanks in advance
You can do it like this
$i=0;
while = ($row = mysql_fetch_row($resource)){
if($i==0){
?><ul class="row box2"><?php
}
?>
<li class="span4"><img src='<?php echo $row['image']?>'></img></li>
<?php
$i++;
if($i==4){
?></ul><?php
$i=0;
}
}
Use array_chunk to devide you main Array with all images into small array with 4 images
as example:
$mainArray;// here the value of all images from db
$resultArray = array_chunk($mainArray, 4); //now you have arrays which include 4 images
And then use foreach to build block as you want
<?php foreach ($resultArray as $minArray){ ?>
<ul class="row box2">
<?php foreach ($minArray as $array){ ?>
<li class="span4">
<img><?php echo $array['img']?></img>
</li>
<?php } ?>
</ul>
<?php } ?>
I am not sure if i understand your questing correctly but you can use for loops . Is this what you want?
var x;
var y = 1;
for (var i=0;i<10;i++)
{
x = x + '<ul class="row box' + i + '">
<li class="span4">
<img> '+ imageArray[y] +' </img>
</li>
<li class="span4">
<img> '+ (imageArray[y] +1) +'</img>
</li>
<li class="span4">
<img>'+ (imageArray[y] + 2) +' </img>
</li>
<li class="span4">
<img>'+ (imageArray[y] + 3) +'</img>
</li>
</ul>';
y++;
}

Place DIV's in a containing DIV based on a numeric value

Ive got the follow PHP:
<div class="slide-background">
<div class="slide">
<?php foreach (array_chunk($items->submenu, $linkCount) as $items): ?>
<?php if (12 / $cols == 1):?>
<div class="col-md-12">
<?php else: ?>
<div class="col-md-<?php echo 12 / $cols; ?>">
<?php endif; ?>
<ul>
<?php foreach($items as $submenu): ?>
<?php echo $submenu; ?>
<?php endforeach; ?>
</ul>
</div>
<?php endforeach; ?>
</div>
<ul class="pager">
<li>prev</li>
<li>next</li>
</ul>
</div>
</div>
basically it calculates how many links to display and how many columns, but i now need to place the links in <div class="slide"></div>, but based on the columns.. so basically i need to say if $cols = 2 place two div's in a div and close.. so its basically how many every $cols it should place so many div's in that div..
Its Confusing for me to even explain.. I think Ive explained it rather well above.. If not place say so and ill try again..
Any Help Greatly Appreciated..
UPDATE:
thanks to Hans ive now have the following:
<?php $linksPerColumn = ceil($linkCount / $cols); $linkCounter = 0;?>
<div class="slide-background">
<div class="slide">
<div class="col-md-<?php echo 12 / $cols ?>">
<ul>
<?php foreach ($items->submenu as $link): ?>
<?php $linkCounter++;?>
<?php if($linkCounter % $linksPerColumn == 0):?>
</ul>
</div>
<div class="col-md-<?php echo 12 / $cols ?>">
<ul>
<?php endif; ?>
<?php echo $link; ?>
<?php endforeach; ?>
</ul>
</div>
</div>
<ul class="pager">
<li>prev</li>
<li>next</li>
</ul>
</div>
</div>
only problem is when there's only one column and i need 2 links and then for it to close the div and the ul and start new ones.. right now it does that except for everyone and not for every two links...
You could use modulus for this one. You should calculate how many items you need per column. And then create a close and open div for example:
<?
$linksPerColumn = 4;
if ($linkCount > 4){
$linksPerColumn = ceil ($linkCount / $amountOfColums);
}
$linkCounter = 0;
?>
<div class="slide-background">
<div class="slide">
<?
foreach ($links as $link)
{
$linkCounter++;
?>
// Do your HTML Here.
<?
if($linkCounter % $linksPerColumn = 0)
{
?>
</div>
<div class="slide">
<?
}
?>
</div>
</div>
// Rest of the HTML here.
I think this should do the trick for you.

Categories