Add custom rows in a foreach list - php

This is my foreach list:
foreach ($items as $key => $item):
if (++$i == 21) break;
$output.='<div class="row-fluid"><div class="span12 block">
<div class="pull-left">
'.$item->title.'
</div>
<div class="pull-right">
<p class="muted">'.date("m/d/Y", $item->date).'</p>
</div>
<div class="clearfix"></div>
</div></div>';
endforeach;
echo $output;
The result is a well orderd list of 21 items picked from an xml feed. What i'm trying to do is to add a custom row between (for example) line 10 and 11.
Can anyone suggest me a good way?

You can do that by adding a simple if statement. If you want every 10th line to have that you can use mod operator %.
foreach ($items as $key => $item):
if (++$i == 21) break;
if ($i == 9) {
$output .= '<div>NEW LINE </div>';
}
$output.='<div class="row-fluid"><div class="span12 block">
<div class="pull-left">
'.$item->title.'
</div>
<div class="pull-right">
<p class="muted">'.date("m/d/Y", $item->date).'</p>
</div>
<div class="clearfix"></div>
</div></div>';
endforeach;
echo $output;

You can use flag variables.
Before loop set initial value of a variable $rowcount=1
and between loop you can increment this variable from +1.
and check
<code>
if($rowcount=10)
{
//do something
}
</code>
Use this solution

Related

Output foreach-item in <div>, but output every 2nd and 3rd item in wrapping div

I have an array with items: $array = ['item 1','item 2','item 3','item 4','item 5','item 6','item 7']
I am looking for the following HTML:
<div class="big">Item 1</div>
<div>
<div class="small">Item 2</div>
<div class="small">Item 3</div>
</div>
<div class="big">Item 4</div>
<div>
<div class="small">Item 5</div>
<div class="small">Item 6</div>
</div>
<div class="big">Item 7</div>
In text: Every 3rd item (including the first) have to have their own div, while the 2nd and 3rd items get a wrapping div.
I've come up with the following loop, but I'm pretty sure it's not going to work in the long run, since it'll probably end the loop with an opening div, since I keep on opening a new one after each BIG ITEM.
$i = 0;
foreach($array as $item) {
<?php
if($i % 3 == 0) {
if($i == 0) {?>
<div class="big">
Item <?= $i; ?>
</div>
<div>
<?php } else { ?>
</div>
<div class="big">
Item <?= $i; ?>
</div>
<div>
<?php } ?>
<?php } else { ?>
<div class="small">
small item
<?= $i; ?>
</div>
<?php } ?>
<?php
$i++;
}
I feel like I'm close, but it also feels wrong to start and close divs in $is where it doesn't belong. Maybe the only thing I'm missing is checking if $i equals the length of the array, and then don't open a new <div> after a big item?
You can use simple if-elseif-else construct to print the divs.
If the index of the current element % 3 is 0, it is a big div, else it is a small div.
If the index of the current element % 3 is greater than 0, it is a small div.
If it is 1, prepend an opening div tag.
If it is 2, append a closing div tag.
Snippet:
<?php
foreach ($array as $idx => $set) {
$mod = $idx % 3;
if($mod === 0){
echo "<div class='big'>$set</div>";
}elseif($mod === 1){
echo "<div><div class='small'>$set</div>";
}else{// if $mod is 2
echo "<div class='small'>$set</div></div>";
}
}
Online Demo
Alternatively, use array_chunk then pick out the first item with array_shift, then join the remaining.
<?php
$array = array_chunk(['item 1','item 2','item 3','item 4','item 5','item 6','item 7'], 3);
foreach ($array as $set) {
echo '<div class="big">'.array_shift($set).'</div>';
if (count($set)) echo '<div><div class="small">'.implode('</div><div class="small">', $set).'</div></div>';
}
?>
Result
<div class="big">item 1</div>
<div>
<div class="small">item 2</div>
<div class="small">item 3</div>
</div>
<div class="big">item 4</div>
<div>
<div class="small">item 5</div>
<div class="small">item 6</div>
</div>
<div class="big">item 7</div>
Example: https://3v4l.org/URB3D
Here you are my simple answer: I think you don't need to use additional counter in case that interpreter adds indexes to array:
$array = ['item 1','item 2','item 3','item 4','item 5','item 6','item 7'];
foreach($array as $key=>$da){
$a = $key % 3;
if($a === 0){
echo "<div class=\"big\">" . $da . "</div>\n";
}
else{
if($a === 1)
echo "<div>\n";
echo " <div class=\"small\">" . $da . "</div>\n";
if($a === 2)
echo "<div>\n";
}
}

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>

Bootstrap how to foreach with columns inside

I have a foreach and I want to place 4 columns then break in a new row and start again but for some reason i got the column number 5(test2) bad pushed like this picture:
should be like this:
here is the code to generate that:
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">
Secciones
</div>
<div class="panel-body">
<div class="row">
#foreach ($boards as $board)
<div class="col-md-3">
<h3>{{$board->boaName}}</h3>
#foreach ($subboards as $subboard)
#if($subboard->boaId == $board->id)
<ul>
<li>{{$subboard->subboaName}}</li>
</ul>
#endif
#endforeach
</div>
#endforeach
</div>
</div>
</div>
</div>
</div>
</div><!--End container-->
Try moving the foreach loop outside of the <div class="row">? If that doesn't work do you think you could mock this up in a jsFiddle example?
You need a test after 4 iterations to close and open again the row div.
If you know how many columns to expect, you could do the following (I've ommited your inner content of each column for my example - I've also left the counter in so you can see the incrementation for testing):
$i = 1;
foreach($boards as $board) {
if($i == 1 || $i == 5 || $i == 9) {
echo "<div class='row'>";
echo "<div class='col-md-3'>" . $i++ . "</div>";
}
elseif($i%4 == 0) {
echo "<div class='col-md-3'>" . $i++ . "</div>";
echo "</div>";
} else {
echo "<div class='col-md-3'>" . $i++ . "</div>";
}
}
What's happening here is if the column count is the 4th iteration, it should echo out an opening <div class="row"> as well as a column. If the current column is divisible by 4, it should echo out a column with an extra closing </div> (to close the row class.)
If the current count is neither of the above, it simply echo's out a column.
You can, of course, mod the above if the amount of potential columns is unknown.

Always show specific result at the end of a for each loop

I got a project page that echoes multiple projects in a foreach loop, and every 4 results it starts a new row on the page.
However I got an element that always needs to be shown as the last result. How can I achieve that?
My foreach loop:
<?
$tel = 1;
foreach ($projectcr as $project) {
$article_images = $project['images']; // Get image parameters of the article
$pictures = json_decode($article_images); // Split the parameters apart
$introtext = $project['introtext'];
if ($project['title'] != '') {
if($tel == 1) {
echo '<div class="row">';
}
echo '
<div class="col-xs-12 col-sm-6 col-lg-3 js-wpg-item" data-categories="gardening">
<a class="card portfolio-grid__card js-wpg-card" href="project/'.$project['alias'].'.html">
<img src="cms/'.$pictures->{'image_intro'}.'" class="card-img-top portfolio-grid__card-img wp-post-image" alt="19" height="240" width="360">
<div class="card-block portfolio-grid__card-block">
<h5>'.$project['title'].'</h5>
<p>'.$project['created'].'</p>
</div>
</a>
</div>'
;
if(($tel % 4) == 0){
echo '</div> <div class="row">';
}
$tel++;
}
}
if(($tel % 4) != 0){
echo '</div>';
}
?>
The element I want to be shown as last block:
<div class="row">
<div class="col-xs-12 col-sm-6 col-lg-3 js-wpg-item" data-categories="">
<div class="portfolio-grid__card portfolio-grid__card--dummy js-wpg-card" href="projects/">
<div class="portfolio-grid__card-block text-center">
<span class="fa fa-cloud-upload fa-2x"></span>
<h5>Uw volgende project hier?</h5>
<p class="portfolio-grid__card-text">
NEEM CONTACT OP
</p>
</div>
</div>
</div><!-- /.col -->
</div><!-- /.row -->
This has the following result:
The element is now shown outside the row, while I need it to be inside the row (but only the last one).
Change your last if condition just after ending foreach
if(($tel % 4) != 0){
//echo div.col-... inside .row started in loop
echo '<div class="col-xs-12 col-sm-6 col-lg-3">always to be shown at last</div>';
//end .row
echo '</div>';
}
Add the content you want to show at the end of the loop. Don't check the condition and add the closing tag for row div, because it will fail to add the close tag if modulus of $tel is equal to zero. Your last content should be shown in new row but it will not close the tag.
$last = <div class="col-xs-12 col-sm-6 col-lg-3 js-wpg-item" data-categories="">
<div class="portfolio-grid__card portfolio-grid__card--dummy js-wpg-card" href="projects/">
<div class="portfolio-grid__card-block text-center">
<span class="fa fa-cloud-upload fa-2x"></span>
<h5>Uw volgende project hier?</h5>
<p class="portfolio-grid__card-text">
NEEM CONTACT OP
</p>
</div>
</div>
</div>
foreach($projectcr as $project) {
...//your code
...
}
echo $last. '</div>';
There are multiple ways to achieve that but can't you just add a element to your array?
$p = [];
$p['title'] = 'Uw volgende project hier?';
$p['created'] = 'NEEM CONTACT OP'
array_push($projectcr, $p);
A other way to do it is to check if its the last element in the array
$lastElement = end($array);
// you code
if($project == $lastElement){
//add the static block
}

PHP Iterate 12 items perform echo on every third

Hi I have been chasing my tail for a while on this one and wondered if someone could solve my headache.
Basically I am rendering 12 items to the page. Each 3 items need to be wrapped in a row like:
<div class='row'>
<div class='item'>
</div>
<div class='item'>
</div>
<div class='item'>
</div>
</div>
<div class='row'>
<div class='item'>
</div>
<div class='item'>
</div>
<div class='item'>
</div>
</div>
<div class='row'>
<div class='item'>
</div>
<div class='item'>
</div>
<div class='item'>
</div>
</div>
<div class='row'>
<div class='item'>
</div>
<div class='item'>
</div>
<div class='item'>
</div>
</div>
Thanks in advance.
Hi I think some code would help:
$i=0;
foreach($posts as $p) {
$i++
}
So basically within the for each I will be outputting a row and 3 items.The results are coming from a database query. I have tried a few different approaches such as
if($i == 1) {echo "<div class='row'>";}
if ($counter % 4 == 0) {
echo "</div><div class='row'>";
}
However I keep failing, please note these are just snippets of code.
You need to use two loops:
// Outer loop for each row
for ($row = 0; $row < 4; $row++) {
echo '<row>';
// Inner loop for the items
for ($item = 0; $item < 3; $item++) {
echo '<item>';
}
echo '</row>';
}
You should have done it yourself. it needs to know very basic of loop.
try like this:
for($i=0;$i <= 3; $i++){ //outer loop for 12 times
echo "<row>"; // start row
for ($j=0;$j<3;$j++){ // inner loops for echoing 3 times
echo "<item>"; //echo item
}
echo "</row>"; // end row
}
demo : https://eval.in/107129
I have used "\n" for new line in demo. if you needed new line then you can use <br />

Categories