Displaying array contents in pairs - php

I'm trying to make a website that displays all userprofiles. I want to wrap every two users in a <div>, until there is no left. So say we have 19 arrays consisting of userprofileinfo in $info - the following code will work fine, but will print out the 20th out as an empty div, which I want to prevent. What to do here?
$info = mysqli_fetch_all($result, MYSQLI_ASSOC);
for ($count = 0; $count <= mysqli_num_rows($result) - 1; $count += 2) {
echo <div class="row">
echo "<div>".print_r($info[$count])."</div>";
echo "<div>".print_r($info[$count+1])."</div>";ยจ
echo </div>
}

I think you might overthinking this. Why not simply use array_chunk()?
$info = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach (array_chunk($info, 2) as $chunk) {
echo '<div class="row">';
foreach ($chunk as $element) {
echo "<div>".$element['name']."</div>";
}
echo '</div>';
}
The way array_chunk() works is that it will group the array elements into chunks of a given size. You can have a double loop. The inner loop will iterate on each chunk and display both elements.

Just to provide a slightly cleaner version of Yvan1263's answer using OPs updated code (having fixed quotes).
$info = mysqli_fetch_all($result, MYSQLI_ASSOC);
for ($count = 0; $count <= count($info) - 1; $count += 2) {
echo '<div class="row">';
echo "<div>".print_r($info[$count])."</div>";
if (isset($info[$count+1])) {
echo "<div>".print_r($info[$count+1])."</div>";
}
echo </div>
}

You can just do this:
$info = mysqli_fetch_all($result, MYSQLI_ASSOC);
for ($count = 0; $count <= mysqli_num_rows($result); $count += 2) {
if($count+1 >= mysqli_num_rows($result)) {
/* IF MAX IS MORE THAN ENTRIES NUMBER */
echo "<div>".print_r($info[$count])."</div";
}
else {
echo "<div>".print_r($info[$count])."</div";
echo "<div>".print_r($info[$count+1])."</div";
}
}
NB: Use PDO instead of MySQLi.

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.

div's with each 6 results in it PHP MYSQL

<div>
<?php if ($result->num_rows > 0) {
$i=1;
while($row = $result->fetch_assoc()) {
if( $i % 6 == 0 )
{ ?>
</div>
<div>
<?php } ?>
<h4><?php echo $row["city"] ?></h4>
<h6><?php echo $row["info"] ?></h6>
<?php $i++;
}
} else {
echo "0 results";
}
?>
</div>
Goal: div's with each 6 rows in it.
When I use $i=1, the first gets 5 results and the other ones get 6.
When I use $i=0 the first one is empty and the other ones get 6.
How to get the first div also filled with 6 results?
Try using array_chunk. That way you don't have to worry where to put your div ends and it's more readable:
$rows = [];
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
foreach (array_chunk($rows, 6) as $subset) {
echo "<div>";
foreach ($subset as $row) {
echo "<h4>{$row["city"]}</h4>"
echo "<h6>{$row["info"]}</h6>"
}
echo "</div>";
}
Using array_chunk as proposed by #Justinas is a good way to refactor code. Yet, taking your original code, the issue is about where you check printed amount. It is wrong to first check output amount as it breaks the logic for the first iteration. Please, refer to the code below.
<div>
<?php
if ($result->num_rows > 0) {
$i = 1;
while ($row = $result->fetch_assoc()) {
# if ($i % 6 == 0) {
# echo '</div><div>';
# }
# move commented code from above to ...
echo "<h4>{$row["city"]}</h4>";
echo "<h6>{$row["info"]}</h6>";
# ... here
if ($i % 6 == 0) {
echo '</div><div>';
}
$i++;
}
} else {
echo "0 results";
}
?>
</div>
You can try setting $i = 0 then excluding it in your if statement with
if ($i > 0 && $i % 6 == 0)
since 0 % 6 == 0.

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
}

variable increment doesn't work

When I launch my web page, increment doesn't work correctly!
It should go like this: $i = from 1 to x (0,1,2,3,4,5,6 etc..).
But instead it jumps over every step giving result of (1,3,5,7 etc..).
Why is this code doing this?
<ul class="about">
<?php
$result = mysql_query("SELECT * FROM info WHERE id = 1");
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
$endBioTxt = explode("\n", $bioText);
for ($i=0; $i < count($endBioTxt);)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
$i++;
}
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
?>
</ul>
Output:
Sometext!(right side)
0
1
Sometext2!(right side)
2
3
...
Please DONT do this as other suggested:
for ($i=0; $i < count($endBioTxt); $i++)
do this:
$count = count($endBioTxt);
for ($i=0; $i < $count; $i++) {
}
No need to calculate the count every iteration.
Nacereddine was correct though about the fact that you don't need to do:
$i++;
inside your loop since the preferred (correct?) syntax is doing it in your loop call.
EDIT
You code just looks 'strange' to me.
Why are you doing:
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
???
That would just set $bioText with the last record (bio value) in the recordset.
EDIT 2
Also I don't think you really need a function to calculate the modulo of a number.
EDIT 3
If I understand your answer correctly you want 0 to be in the left li and 1 in the right li 2 in the left again and so on.
This should do it:
$endBioTxt = explode("\n", $bioText);
$i = 0;
foreach ($endBioTxt as $txt)
{
$class = 'left';
if ($i%2 == 1) {
$class = 'right';
}
echo '<li class="'.$class.'"><div>'.$txt.'</div></li>';
echo $i; // no idea why you want to do this since it would be invalid html
$i++;
}
Your for statement should be:
for ($i=0; $i < count($endBioTxt); $i++)
see http://us.php.net/manual/en/control-structures.for.php
$i++; You don't need this line inside a for loop, it's withing the for loop declaration that you should put it.
for ($i=0; $i < count($endBioTxt);$i++)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
//$i++; You don't need this line inside a for loop otherwise $i will be incremented twice
}
Edit: Unrelated but this isn't how you check whether a number is prime or not
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
This code works, please test it in your environment and then uncomment/comment what you need.
<?php
// This is how query should look like, not big fan of PHP but as far as I remember...
/*
$result = mysql_query("SELECT * FROM info WHERE id = 1");
$row = mysql_fetch_assoc($result);
$bioText = $row['bio'];
$endBioTxt = explode("\n", $bioText);
*/
$endBioTxt[0] = "one";
$endBioTxt[1] = "two";
$endBioTxt[2] = "three";
$endBioTxt[3] = "four";
$endBioTxt[4] = "five";
$totalElements = count($endBioTxt);
for ($i = 0; $i < $totalElements; $i++)
{
if ($i % 2)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
}
/*
// This is how you should test if all your array elements are set
if (isset($endBioTxt[$i]) == false)
{
echo "Array has some values that are not set...";
}
*/
}
Edit 1
Try using $endBioTxt = preg_split('/$\R?^/m', $bioTxt); instead of explode.

Count data and split into two columns

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

Categories