I have 11 news then i want to display like
first column need only one news
second column need 5 news
third column need the rest of 5 news
I tried this but no luck, it shows first column and second column and the rest outside column
$rows = array(
'Title1',
'Title2',
'Title3',
'Title4',
'Title5',
'Title6',
'Title7',
'Title8',
'Title9',
'Title10',
'Title11',
);
$total_rows = count($rows);
$total_cols = $total_rows - 1;// remove first one for the first column
$left_column = ceil($total_cols / 2);
$right_column = $total_cols - $left_column;
$i = 0;
echo "<div class='row'>";
foreach ($rows as $row) {
$i++;
if ($i == 1) {
$class = "primary_post";
echo "<div class='col-md-4 main'>";
} elseif ($i <= $left_column) {
$class = "other_post";
echo "<div class='col-md-4 left'>";
} elseif ($i == $right_column) {
$class = "other_post";
echo "<div class='col-md-4 right'>";
} else {
$class = "other_post";
}
echo "<div class='card {$class}'>$i</div>";
if ($i == 1 || $i == $left_column || $i == $right_column) {
echo "</div>";
} else {
echo "";
}
}
echo "</div>";
The last echo "</div>"; supposed to be in the FOR loop not outside of it.
Also, you can split the array into chunks;
$firstColumn = array_splice($rows,0,1);
$secondColumn = array_splice($rows,0,5);
Rest are in the $rows variable.
So instead of dealing with ifs in for loops, you can use 3 different loops and list items in desired HTML objects.
Related
Suppose I have 10 records, and 2 different classes namely c1, c2
<div class="c2">..content..</div>
<div class="c2">..content..</div>
<div class="c1">..content..</div>
<div class="c1">..content..</div>
<div class="c2">..content..</div>
<div class="c2">..content..</div>
<div class="c1">..content..</div>
<div class="c1">..content..</div>
<div class="c2">..content..</div>
<div class="c2">..content..</div>
i want the if else condition where class order needs to maintained like c2,c2,c1,c1,c2,c2,c1,c1,c2,c2.....so on
foreach(x as y){
if() {
<div class="<?php echo $class1;?>">..content..</div>
} else {
<div class="<?php echo $class2;?>">..content..</div>
}
class order should be c2,c2,c1,c1,c2,c2,c1,c1,c2,c2.....so on
Check the page url http://themesflat.com/html/nah/portfolio-creative.html
You can use a bitwise operator (&) here, and with 2 and this will toggle the class...
$i = 0;
foreach($x as $y){
if($i & 2) {
$class = "1";
} else {
$class = "2";
}
echo "<div class=$class>..content..</div>";
$i++;
}
I've extracted the echo out as this keeps it consistent, just have a variable for the class you want to have and put that in the if instead.
You can do it with a separate counter
$current = 'c2';
$count = 1;
for ($i = 0; $i < 10; $i++) {
echo '<div class="'. $current . '">..content..</div>';
if ($count == 2) {
$current = $current == 'c1' ? 'c2' : 'c1';
$count = 0;
}
$count++;
}
Demo: https://3v4l.org/7ftjg
This will of course work just as well in a foreach-loop.
Note: If it's only about styling the divs differently, you could do this in CSS alone. Here's a similar question and answer: nth-child: how to pick elements in groups of two
I'm pretty sure you can resolve the problem via css pseudo class :nth-of-type but if you prefered PHP you can try the following example.
<?php
$class_types = ['c2', 'c1'];
$records = array_fill(0, 10, '..content..'); // replace with your records
$records_length = count($records);
$html_output = '';
foreach ($records as $index => $item) {
$type = floor($index / $records_length * $records_length / 2) % 2;
$class = $class_types[$type];
$html_output .= sprintf('<div class="%s">%s</div>', $class, $item);
}
echo $html_output;
Try this code:
$counter = 1;
for($i=0;$i<=10; $i++){
if($counter==1 or $counter==2) {
echo '<div class="c1">..content..</div>';
} else {
echo '<div class="c2">..content..</div>';
}
if($counter==4){
$counter=0;
}
$counter++;
}
?>
How about we chunk the main array into an array or arrays of two
like
<?php
$chunked_array = array_chunk( $your_array , 2 );
// This will give us an array of 2 elements array
// now we will loop
for( $i = 1 ; $i < count( $chunked_array ); $++ ){
$contents = $chunked_array[$i];
foreach( $contents as $content ){
if ( $i%2 == 0 ){
//<div class="<?php echo $class1;?>">..content..</div>
}else{
//<div class="<?php echo $class2;?>">..content..</div>
}
}
}
using this way we have one loop and it will always be in a group of two even when your data grow or shrink
My code is below:
function portfolio_gallery() {
global $conn;
$query = $conn->query("SELECT codename, namegroup, features, title, showimage FROM portfolio ORDER BY id DESC");
if ($query->num_rows > 0) {
// output data of each row
echo '<div>';
$i = 0;
while($row = $query->fetch_assoc()) {
$i++;
if ($row["showimage"]) {
if($i % 9 == 0){
echo '</div><div>';
}
echo '<a class="imgpop" href="images/portfolio/large/'.$row["codename"].'.jpg" rel="'.$row["namegroup"].'" title="'.$row["title"].' - '.$row["features"].'"><img src="images/portfolio/thumb/'.$row["codename"].'.jpg" alt="'.$row["title"].'" width="348"/><span class="imgpop-caption">'.$row["title"].'</span></a>';
}
}
echo '</div>';
}
}
portfolio_gallery();
I wanted to echo </div><div> for every after 9th item of the loop but every time I executed the code, the first echo only happened after 8 items instead of 9, but the rest was every 9th.
You have to increment
$i
after
if($i % 9 == 0)
follow the syntax example i worked out its working
<?php
$j=0;
for($i=0;$i<=50;$i++)
{
if($j==9)
{
echo $j.'hioiiiiiii<br/>'; //echo "</div><div>";
$j=-1;
}
$j++;
}
?>
Please try this :)
<?php
function portfolio_gallery() {
global $conn;
$query = $conn->query("SELECT codename, namegroup, features, title, showimage FROM portfolio ORDER BY id DESC");
if ($query->num_rows > 0) {
// output data of each row
echo '<div>';
$i = 0;
while($row = $query->fetch_assoc()) {
if ($row["showimage"]) {
if($i % 9 == 0){
echo '</div><div>';
}
echo '<a class="imgpop" href="images/portfolio/large/'.$row["codename"].'.jpg" rel="'.$row["namegroup"].'" title="'.$row["title"].' - '.$row["features"].'"><img src="images/portfolio/thumb/'.$row["codename"].'.jpg" alt="'.$row["title"].'" width="348"/><span class="imgpop-caption">'.$row["title"].'</span></a>';
}
$i++;
}
echo '</div>';
}
}
declare $i = 1 and Write $i++ at the end of while loop.
if ($query->num_rows > 0) {
// output data of each row
echo '<div>';
$i = 1; // declare $i = 1 here
while($row = $query->fetch_assoc()) {
if ($row["showimage"]) {
if($i % 9 == 1){ // 10 , 19 ,28
echo '</div><div>';
}
echo '<a class="imgpop" href="images/portfolio/large/'.$row["codename"].'.jpg" rel="'.$row["namegroup"].'" title="'.$row["title"].' - '.$row["features"].'"><img src="images/portfolio/thumb/'.$row["codename"].'.jpg" alt="'.$row["title"].'" width="348"/><span class="imgpop-caption">'.$row["title"].'</span></a>';
}
$i++; // increment at end of the loop
}
echo '</div>';
}
I was able to solve it by modifying the condition:
So instead of: if($i % 9 == 0) {...}
I used: if($i!=0 && $i % 9 == 0) {...}
And also placing $i++ at the end of while loop.
Heres the scenario, I have array with 7 items and I want to separate them in every fourth iteration.. just like this
$counter2 = 0;
$counter3 = 0;
$counter4 = 0;
$sample_array = array('Aso','Pusa','Daga','Kuting','Tuta','Bubwit','Boom');
foreach($sample_array as $sample_array_value)
{
if(++$counter4 % 4 == 0)
{
echo $sample_array_value;
echo "</div>";
}
elseif(++$counter3 % 3 == 0)
{
echo $sample_array_value;
}
elseif(++$counter2 % 2 == 0)
{
echo $sample_array_value;
}
else
{
echo "<div>";
echo $sample_array_value;
}
}
The out put will be div AsoPusaDagaKuting /div div TutaBubwitBoom
The problem is when it ends in iteration that doesn't count 4 it doesn't give the separator ending..
I need it to output div AsoPusaDagaKuting /div div TutaBubwitBoom /div
Thanks in advance...
You can split it with array_chunk, implode the new subarrays of 4 with array_map, then echo it with implode.
$sample_array = array('Aso','Pusa','Daga','Kuting','Tuta','Bubwit','Boom');
echo "<div>", implode("</div><div>", array_map("implode", array_chunk($sample_array, 4))), "</div>";
Result:
<div>AsoPusaDagaKuting</div><div>TutaBubwitBoom</div>
Try this:
$i = 0;
foreach($sample_array as $sample_array_value)
{
if(++$counter4 % 4 == 0)
{
echo $sample_array_value;
echo "</div>";
}
elseif(++$counter3 % 3 == 0 || ++$counter2 % 2 == 0)
{
echo $sample_array_value;
}
else
{
echo "<div>";
echo $sample_array_value;
}
$i++;
}
if ($i % 4 != 0) {
echo "</div>";
}
You are printing the values inside every condition, then why not use echo once outside any condition? Also you want to close and open a div tag for the forth element, then only 1 counter would do the trick. Only this will work -
$sample_array = array('Aso','Pusa','Daga','Kuting','Tuta','Bubwit','Boom');
$i = 0;
echo "<div>";
foreach($sample_array as $sample_array_value)
{
if($i > 0 && $i % 4 == 0)
{
echo "</div><div>";
}
echo $sample_array_value;
$i++;
}
echo "</div>";
Output
<div>AsoPusaDagaKuting</div><div>TutaBubwitBoom</div>
i have this php mysql query
<?php
$product = mysql_query('SELECT * FROM products LIMIT 6 ');
$pro = mysql_fetch_assoc($product);
?>
Now that query will return 6 products from database and what i want to do is echo 3 products inside a <div> and the other 3 products inside another <div> like this
<div class="first-3>
///Here i want to echo 3 products from the query from 1-3
<?php echo $pro['title']; ?>
</div>
<div class="second-3>
///Here i want to echo the rest 3 products of the query from 4-6
<?php echo $pro['title']; ?>
</div>
<?php
$num = 6;
$product = mysql_query('SELECT * FROM products LIMIT $num');
$firstDiv = "";
$secondDiv = "";
$i = 0;
while ($pro = mysql_fetch_assoc($product)) {
if ($i < ($num /2)) {
$firstDiv .= $pro['title'];
}
else {
$secondDiv .= $pro['title'];
}
$i++;
}
?>
And:
<div class="first-3>
<?php $firstDiv ?>
</div>
<div class="second-3>
<?php $secondDiv ?>
</div>
Iterate and output the values.
<?php
$product = mysql_query('SELECT * FROM products LIMIT 6 ');
$i = 1;
echo '<div class="first-3">';
while ( $pro = mysql_fetch_assoc($product) ) {
if ($i === 3) {
echo '</div><div class="second-3">';
}
echo $pro['title'];
$i++;
}
echo '</div>';
?>
Note that it's not safe to use mysql_query, you should be using mysqli or preferrably PDO.
mysql_fetch_assoc is used to retrieve a row in the resultset.
Doc: http://php.net/manual/es/function.mysql-fetch-assoc.php
A loop is required to iterate on each row.
A very simple example:
// Get a collection of 6 results
$products = mysql_query('SELECT * FROM products LIMIT 6 ');
// iterate over the 6 results
$i=0;
echo '<div class="first-3>';
while ($pro = mysql_fetch_assoc($products)) {
$i++;
// Print an item
echo $pro["title"];
// If 3 items are printed end first div and start second div
if($i==3){
echo '</div><div class="second-3">';
}
}
echo '</div>';
// Free the collection resources
mysql_free_result($products);
Just set up a counter to divide in groups of 3:
$count = 0;
while (...)
{
// your code
$count++;
if ( ($count % 3) === 0 )
{
echo '</div><div class="...">';
}
}
Please note that the mysql_* functions are deprecated and you should switch to PDO or mysqli.
$product = mysqli_query($conn, 'SELECT * FROM products LIMIT 6 ');
$results = array();
while($pro = mysqli_fetch_assoc($product)) {
$results[] = $pro;
}
echo '<div class="first-3">';
for($i = 0; $i < 3; $i++) {
echo $results[$i]['title'];
}
echo '</div><div class="second-3">';
for($i = 3; $i < 6; $i++) {
echo $results[$i]['title'];
}
echo '</div>';
Everytime you get the multiple of 3, ($k % 3 == 0) you will increment the flag variable, you can do then some conditions with the variable flag, i used here iterators because the hasNext() beauty.
Example
$pro = array(1, 2, 3, 4, 5, 6);
$flag = 0;
$pro = new CachingIterator(new ArrayIterator($pro));
foreach ($pro as $k => $v) {
// if multiples 3
if ($k % 3 == 0) {
$flag++;
if ($flag == 1) {
echo '<div class="first-3" style="border:1px solid black;margin-bottom:10px;">';
} else if ($flag == 2) {
echo '</div>'; // Closes the first div
echo '<div class="second-3" style="border:1px solid red">';
}else{ // if you have more than 6
echo '</div>';
}
}
// insert Data
echo $v . '<br/>';
if (!$pro->hasNext())
echo '</div>'; // if there is no more closes the div
}
I am tweaking a facebook album class that loops and echos data. The problem is that when it echos it loops into one column and I want to separate it into 2 columns. This is what it looks like now:
foreach($json->data as $v)
{
echo "<a class='ImageLink' rel='lightbox[photos]' href = '".$v->source."'><img style='margin:10px;' width='110px' src='".$v->picture."' /></a>";
}
I am trying to do something like so:
$count = count($json->data);
$half_count = $count/2;
echo "<ul class='float:left;'>";
$counter = 0;
foreach($json->data as $v)
{
if ($counter == $half_count +1){echo "<ul class='float:left;'>";}
echo "<li>". $v->picture ."</li>";
if ($counter == $half_count){ echo "</ul>";}
$counter++;
}
echo "</ul>";
But when I use the count function on $json->data and echo that it gives me an array. Please help;
"But when I use the count function on $json->data and echo that it gives me an array." <- Count will always return an int.
Try the following correction to your code:
$count = count($json->data);
$half_count = ceil($count / 2); // make sure to ceil to an int. This will have your first column 1 larger than the second column when the count is odd
echo '<ul style="float:left">';
$counter = 0;
foreach($json->data as $v) {
echo '<li>' , $v->picture , '</li>';
$counter += 1;
if ($counter == $half_count && $count != 1) {
echo '</ul><ul style="float:right">';
}
}
echo "</ul>";