New containing div after every 3 records
As tadman stated in the comment under your question. The best approach should use a modulus operator (%
) with 3
.
Place your separating condition at the start of each iteration. (Demo)
Like this:
$x=0; // I prefer to increment starting from zero.
// This way I can use the same method inside a foreach loop on
// zero-indexed arrays, leveraging the keys, and omit the `++` line.
echo "<div class=\"row\">";
foreach($rows as $row){
if($x!=0 && $x%3==0){ // if not first iteration and iteration divided by 3 has no remainder...
echo "</div>\n<div class='row'>";
}
echo "<div>$row</div>";
++$x;
}
echo "</div>";
This will create:
<div class="row"><div>one</div><div>two</div><div>three</div></div>
<div class='row'><div>four</div><div>five</div><div>six</div></div>
Late Edit, here are a couple of other methods for similar situations which will provide the same result:
foreach(array_chunk($rows,3) as $a){
echo "<div class=\"row\"><div>",implode('</div><div>',$a),"</div></div>\n";
}
or
foreach ($rows as $i=>$v){
if($i%3==0){
if($i!=0){
echo "</div>\n";
}
echo "<div class=\"row\">";
}
echo "<div>$v</div>";
}
echo "</div>";
To clarify what NOT to do...
Sinan Ulker's answer will lead to an unwanted result depending on the size of your result array.
Here is a generalized example to expose the issue:
Using this input array to represent your pdo results:
$rows=["one","two","three","four","five","six"];
Sinan's condition at the end of each iteration:
$i=1;
echo "<div class=\"row\">";
foreach($rows as $row){
echo "<div>$row</div>";
if($i%3==0)echo "</div>\n<div class='row'>"; // 6%3==0 and that's not good here
// 6%3==0 and will echo the close/open line after the content to create an empty, unwanted dom element
$i++;
}
echo "</div>\n\n";
Will create this:
<div class="row"><div>one</div><div>two</div><div>three</div></div>
<div class='row'><div>four</div><div>five</div><div>six</div></div>
<div class='row'></div> //<--- this extra element is not good
Add div after every three items in a loop?
Your feelings are right.
You can use the $current_post
property of the WP_Query
class to get the index of the post currently displayed in the loop, and then use the modulus operator to make sure you are targeting multiples of three.
So your loop could look like this:
<div class="row container">
<!-- row -->
<div class="twelve columns">
<div class="four columns">
<?php while ( have_posts() ) : the_post(); ?>
<!-- item -->
<div class="four columns">IMAGE HERE</div>
<?php if( $wp_query->current_post % 3 == 0 ) : ?>
</div>
</div>
<!-- row -->
<div class="twelve columns">
<div class="four columns">
<?php endif; ?>
<?php endwhile; ?>
</div>
You might need to improve this implementation. Specifically, make sure that, whatever happens, your HTML closes correctly.
create new row after every 3 column in loop
The code to print row
should be inside foreach
loop in a specific condition. And the condition for printing row should be as:
<?php
foreach ($location_list as $key => $location) {
if ($key % 3 == 0) {
echo '<div class = "row">';
}
echo "<div class ='col-md-4'>
<hr> $location->address </hr>
<hr> $location->name </hr>
<hr> $location->pin </hr>
</div> ";
if ($key % 3 == 2) {
echo '</div>';
}
}
?>
How generate a new div row per 3-4 colums of data
You can wrap group of every 4 columns (div with content) inside wrapper (parent div) and style columns to display inline-block.
<?php
$break = 0;
for($i = 0; $i < 200; $i++)
{
if($break % 4 === 0)
{
echo '<br>open div<br/>'; //your wrapper/row start
}
$break++;
echo $i . ' '; //your column with content
if($break % 4 === 0)
{
echo '<br />close div<br />'; //your wrapper/row end
}
}
Loop row in bootstrap every 3 columns
Edit: Originally I posted this quickly from the top of my head. Thanks, Wael Assaf for pointing out an improvement, which I have used. Also, I have added a couple of changes to the code, now it is versatile and can be used for a variable number of columns you can choose by changing the variable $numOfCols
You need to add a div for each row. Then the floating divs you have, will not just wrap around but instead will be in their own container.
The bootstrap class row
is perfect for this:
Method 1 (not recommended for new versions of HTML and Browser): This method is for older version on HTML and browser because new versions of HTML and browser have inbuild functions to auto close missing tags so when you use code below it will automatically close pre-defined tag <div class="row">
rather than waiting for if
condition to close that tag in result causing improper layout.
Note: you can try and observe result by inspecting elements
<?php
//Columns must be a factor of 12 (1,2,3,4,6,12)
$numOfCols = 4;
$rowCount = 0;
$bootstrapColWidth = 12 / $numOfCols;
?>
<div class="row">
<?php
foreach ($rows as $row){
?>
<div class="col-md-<?php echo $bootstrapColWidth; ?>">
<div class="thumbnail">
<img src="user_file/<?php echo $row->foto; ?>">
</div>
</div>
<?php
$rowCount++;
if($rowCount % $numOfCols == 0) echo '</div><div class="row">';
}
?>
</div>
Uses PHP modulus operator to echo the open and close of each row at the right points.
Method 2 (recommended): This method is to overcome the problem faced by method 1, as a result, causing proper layout for modern browser.
<?php
//Columns must be a factor of 12 (1,2,3,4,6,12)
$numOfCols = 4;
$rowCount = 0;
$bootstrapColWidth = 12 / $numOfCols;
foreach ($rows as $row){
if($rowCount % $numOfCols == 0) { ?> <div class="row"> <?php }
$rowCount++; ?>
<div class="col-md-<?php echo $bootstrapColWidth; ?>">
<div class="thumbnail">
<img src="user_file/<?php echo $row->foto; ?>">
</div>
</div>
<?php
if($rowCount % $numOfCols == 0) { ?> </div> <?php } } ?>
Note: you can try and observe result by inspecting elements
Hope this helps.
New row every 3 items
Besides the aforementioned each_slice
, Rails also has an in_groups_of
method that you can use like so:
<% @items.in_groups_of(3, false).each do |group| %>
<div class="row">
<div class="three columns">
<% group.each do |item| %>
<div class="item">
<%= item.content %>
</div>
<% end %>
</div>
</div>
<% end %>
Pretty much the same as each_slice
, except the scenario of needing to output blank divs becomes much cleaner like so:
<% @items.in_groups_of(3).each do |group| %>
<div class="row">
<div class="three columns">
<% group.each do |item| %>
<div class="item">
<%= item.content if item %>
</div>
<% end %>
</div>
</div>
<% end %>
in_groups_of
pads missing items in the last group with nil
by default, so it will make the last few iterations and the if item
check will make sure it doesn't blow up by calling content
on nil
.
in_groups
is another fun one to use for view formatting.
PHP add div style=clear /div in a loop after every 4 records
Use a modulos
$i = 1;
while ($row = mysql_fetch_array($result) {
echo '<div>'.$row.'</div>';
if (($i++ % 4) == 0) echo '<div style="clear:both;"></div>';
}
You should not use mysql
as it is deprecated. Instead, use MySQLi
or PDO
.
React: Render new row every 4th column
Group your products into rows of (at most) 4 elements, i.e.
[1,2,3,4,5,6,7,8] => [ [1, 2, 3, 4], [5, 6, 7, 8 ] ]
Iterate over the groups to generate rows, and in an inner loop iterate over the items to display columns
To calculate the number of rows, given 4 items per row, use Math.ceil(props.products.length / 4)
. Then create an array of rows. Given 2 rows (for 8 items): Array(2)
. Since you can't map
an array of uninitialized elements, you can use spread syntax: [...Array(2)]
which returns [ undefined, undefined ]
.
Now you can map these undefined
entries into rows: for each row take 4 elements from products: [ undefined, undefined ].map( (row, idx) => props.products.slice(idx * 4, idx * 4 + 4) ) )
(edit note changed to slice
since splice
mutates the original array). The result is an array of arrays (rows of items).
You can iterate over the rows, and inside each iteration iterate over the items in given row.
https://jsfiddle.net/dya52m8y/2/
const Products = (props) => {
// array of N elements, where N is the number of rows needed
const rows = [...Array( Math.ceil(props.products.length / 4) )];
// chunk the products into the array of rows
const productRows = rows.map( (row, idx) => props.products.slice(idx * 4, idx * 4 + 4) ); );
// map the rows as div.row
const content = productRows.map((row, idx) => (
<div className="row" key={idx}>
// map products in the row as article.col-md-3
{ row.map( product => <article key={product} className="col-md-3">{ product }</article> )}
</div> )
);
return (
<div>
{content}
</div>
);
}
Javascript every nth, create new row
First of all, no need to handle a count
variable on your own, the .each()
function already supplies an index element (as an optional argument).
With the modulus
operator you can get the remainder from dividing the index
by 3. Then you can tell when do you need to print the opening of the row and the ending of it.
$(data).find('products').each(function(index) {
itemName = $(this).find('itemName').text();
itemDesc = $(this).find('itemDesc').text();
itemID = $(this).find('id').text();
if ((index % 3) == 0) items += '<div class="row-fluid">';
items += '<div class="span3">Col 1</div>';
if ((index % 3) == 2) items += '</div>';
});
if (items.substr(-12) != '</div></div>') items += '</div>';
Related Topics
Wordpress: Loading Multiple Scripts with Enqueue
Getting Multiple Checkboxes Names/Id's with PHP
Run a Ffmpeg Process in the Background
Strict Standards: Only Variables Should Be Assigned by Reference PHP 5.4
PHP File Upload Error Tmp_Name Is Empty
Get Variables from the Outside, Inside a Function in PHP
How to Convert Excel Xls to CSV Using PHP
Laravel - Database, Table and Column Naming Conventions
Laravel 5.2 Cors, Get Not Working with Preflight Options
How to Call a PHP Function from Ajax
How to Validate a Domain Name Using Regex & PHP
Return PHP Object by Index Number (Not Name)
Detecting a Url Using Preg_Match? Without Http:// in the String
Split a Text into Single Words