Count data and split into two columns - php

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>";

Related

how to display 3 column news layout

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.

How to echo every after 9th iteration of a loop? First echo only counted 8 items

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.

php First value of array not displaying

I have the following bit of code and for some reason in the first WHILE loop the first value of $actor_list (when $i = 0) does not display. If I simply echo $actor_list[0] then it displays fine, but in the loop it will not display. I merely get [td][/td] as the output. The remaining values of the array display fine.
Also the line
echo '</tr><tr> </br>';
is not displaying.
What am I missing here? The value of $num_actors is an even number in my test scenario so there doesn't seem to be a reason for the above echo line to be skipped.
$actor_list = explode(" ", $actors);
$num_actors = count($actor_list);
if ($num_actors <= 6) {
foreach ($actor_list as $actor) {
echo '[td]'.$actor.'[/td] </br>';
}
} elseif ($num_actors <= 12) {
if ($num_actors % 2 == 0) {
$half_actors = $num_actors / 2;
while ($i <= ($half_actors - 1)) {
echo '[td]'.$actor_list[$i].'[/td] </br>';
$i++;
}
echo '</tr><tr> </br>';
while ($i <= $num_actors) {
echo '[td]'.$actor_list[$i].'[/td] </br>';
$i++;
}
}
}
You're not initialising the variable $i to 0, which means it will be set to 'null' and thus not reference the 0th index of the array; but when it's then incremented its value will become 1.
Note: [..] Decrementing NULL values has no effect too, but incrementing them results in 1.
See: http://php.net/manual/en/language.operators.increment.php
Try adding:
$i = 0;
before the if statement.
Made a few changes.
This is working for me.
Try it out.
<?php
$actor_list = 'act1 act2 act3 act4 act5 act6';
$actors = explode(" ", $actor_list);
$num_actors = count($actor_list);
//debug
//echo "<pre>";
//print_r($actor_list);
//echo "</pre>";
echo "<table>";
if ($num_actors <= 6) {
foreach ($actors as $actor) {
echo '<tr><td>'.$actor.'</td></tr>';
}
} elseif ($num_actors <= 12) {
if ($num_actors % 2 == 0) {
$half_actors = $num_actors / 2;
while ($i <= ($half_actors - 1)) {
echo '<tr><td>'.$actor_list[$i].'</td></tr>';
$i++;
}
while ($i <= $num_actors) {
echo '<tr><td>'.$actor_list[$i].'</td></tr>';
$i++;
}
}
}
echo "</table>";
?>

PHP Loop determine 4th iteration but if the iteration is less than 4 echo something

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>

Split query results in 2 div's

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
}

Categories