foreach loop with more than one step - php

I am using PDO to get result from database and then using foreach loop to display data.
my code is
$result1=$objPage->getGallery($id);
foreach($result1 as $row)
{
echo "pic1=" . $row['pic'];
echo "pic2=" . $row['pic'];
echo "pic3=" . $row['pic'];
echo "<br>";
}
Actually, I want to display three pictures names in one line and then next 3 names.
But now its printing one name 3 times.

Do something like this:
$result1=$objPage->getGallery($id);
$count = 0;
foreach($result1 as $row)
{
echo "pic" . $count + 1 . "=" . $row['pic'];
if( $count % 3 == 2 )
{
echo "<br>";
}
$count++;
}
Information
Modulo %

first, prepare your data
$data = $objPage->getGallery($id);
$data = array_chunk($data,3);
then output it
<table>
<? foreach($data as $chunk): ?>
<tr>
<? foreach($chunk as $row): ?>
<td><img src="<?=$row['pic']?>"></td>
<? endforeach ?>
</tr>
<? endforeach ?>
</table>

You can use an external flag, like this:
$flag = 0;
$result1=$objPage->getGallery($id);
foreach($result1 as $row) {
echo "pic" . ($flag + 1) . "=" . $row['pic'];
if( $flag % 3 == 0 )
echo "<br>";
$flag++;
}

You could use modulo as suggested by others, but how about this more compact method?
$result1 = $objPage->getGallery($id);
$separators = array('', '', '<br/>');
foreach ($result1 as $index => $row) {
echo 'pic' . ($index % 3) . '=' . $row['pic'] . $separators[$index % 3];
}

Related

$value++ will not add 1 for me in php

Here is my code..
<?php
$files = scandir('audio');
$files = array_slice($files, 2);
$files = array_combine(range(1, count($files)), $files);
foreach ($files as $file) {
$count =0;
echo ++$count . " ";
echo rtrim($file, ".mp3 ");
{ ?>
<br><audio src="audio/<?php echo rtrim($file, " "); ?>" controls="controls"></audio><br>
<?php }
echo "<hr>";
}
?>
Part of that code is
$count =0;
echo ++$count . " ";
As I currently have 4 files in my directory, I was expecting this to echo 1,2,3,4 but instead I got 1,1,1,1
I have also tried the other way round with $count++ (for post/pre) but this gives me 0,0,0,0 what am I doing wrong, please?
Move your count variable out of the for loop:
$count =0;
foreach ($files as $file) {
echo ++$count . " ";
echo rtrim($file, ".mp3 ");
}

How to print multiple arrays with foreach?

I have 2 arrays: post_titles and posts. How do I print them one after another with foreach?
When I use 1 array, it works fine:
<?php foreach ($titles as $row) { ?>
<?php echo $row['post_title'] ?> <br>
<?php } ?>
I want data to be printed like this:
Title
Post
<br>
Title
Post
<br>
etc.
If each item in the titles and post correspond to each other (eg titles[1] and posts[1], titles[2] and posts[2]), you could use a for loop.
eg.
for($i = 0; $i < count($titles); $i++) {
echo $titles[$i];
echo $posts[$i];
echo "<br>";
}
or
foreach ($titles as $i => $value ){
echo $value ." <br>" . $posts[$i] . " <br>";
}
If the array have the same index key you can use this
<?php
foreach($titles as $key=> $value) {
echo $value . ' - ' $post[$key] . '<br>';
}
?>
If the 2 arrays are in sync i.e. the same length and arr1(0) equates to arr2(0) then its easy
<?php
foreach ($post_titles as $i => $title) {
echo $title . '<br>' . $posts[$i] . '<br>';
}
?>

PHP members page carrying down to new line

I have a page on my site that shows a member directory. I want the members to be listed 3 per row, before it goes to the next row. The code I have, does this for the very first row - but on the second row, its all on one line and doesnt carry down.
The profiles are showing up like this:
uuu
uuuuuuuuuuuuuuuuuuuuuuuuuuu
When they should be doing this:
uuu
uuu
uuu
uuu
This is what my code looks like:
<table>
<tr>
<td colspan="4"><h1>Member Directory</h1></td></tr>
<tr>
<td>
<?php
while($row = mysql_fetch_array($result)) {
if (empty($row['profile']) === false){
echo '<img src="', $row['profile'], ' "width="125">';
} else {
echo '<img src="../../images/template/avatar.png">';
}
echo '</td><td>';
echo '' . ucfirst($row['username']) . '<br />';
echo "Location: " . $row['location'] . "<br />";
echo '</td><td>';
if ($i++ == 2) echo '</td></tr><tr><td>';
}
?>
</td>
</tr>
</table>
Any help would be greatly appreciated, thanks!
Use
if (++$i % 3 == 0) echo '</td></tr><tr><td>';
Explanation:
First of all ++$i first increments $i, and then uses it in whatever is next, this makes for more readable code.
Second, the % is the modulus, which means it sortof subtracts 3 from $i until it is not possible anymore. E.g. 9 % 3 == 0, and 11 % 3 == 2 and so on. This means we know that we have printed 3 rows whenever $i % 3 equals 0.
try this one
<table>
<tr>
<td colspan="4"><h1>Member Directory</h1></td>
</tr>
<?php
$count=0;
while($row = mysql_fetch_array($result))
{
$count+=1;
if($count%3==1)
{
echo '<tr>';
}
echo '<td>';
if (empty($row['profile']) === false){
echo '<img src="', $row['profile'], ' "width="125">';
} else {
echo '<img src="../../images/template/avatar.png">';
}
echo '</td>';
echo '<td>';
echo '' . ucfirst($row['username']) . '<br />';
echo "Location: " . $row['location'] . "<br />";
echo '</td>';
if($count%3==0)
{
echo '</tr>';
}
}
if($count%3!=0)
{
echo '</tr>';
}
?>
</table>
You didn't reset the value of $i, so it kept increasing; another issue is that if you have only seven items, the last row should have four empty cells. So the loop condition needs to be augmented with a row completion status:
$i = 0;
while (($row = mysql_fetch_array($result)) !== false || $i != 0) {
if ($i == 0) {
echo '<tr>'; // start of new row
}
if ($row !== false) {
echo '<td>';
if (empty($row['profile'])) {
echo '<img src="', $row['profile'], ' "width="125">';
} else {
echo '<img src="../../images/template/avatar.png">';
}
echo '</td><td>';
echo '' . ucfirst($row['username']) . '<br />';
echo "Location: " . $row['location'];
echo '</td>';
} else {
echo '<td></td><td></td>'; // no more data
}
$i = ($i + 1) % 3; // advance
if ($i == 0) {
echo '</tr>'; // end of the row
}
}

How to show the value of two related arrays in php?

I have two arrays myarray1 has name of images and myarray2 has the address of images,
I am going to show image names and their addresses in pagination but do not know how to complete the code.
$pages = array_chunk($myarray1,10);
$addrs = array_chunk($myarray2,10);
$page_number = 1
$count = 0;
echo'<table>';
echo'<tr>';
foreach ($pages[$page_number] as $i) {
$counter++;
if ($count == 5) {
echo '</tr><tr>';
$counter = 0;
}
echo'<td>'.$i. " AND " . <<Value of addrs array goes here
echo'</td>';
}
.......
I'll do it on this way
$count = 1;
foreach ($pages[$page_number] as $key => $i) {
if ($count % 5 == 0) {
echo '</tr><tr>';
echo '</div>';
echo '</div>';
}
echo'<td>'.$i. " AND " . $addrs[$page_number][$key]
echo'</td>';
$count++; // increase at the end.
}
if you can try to var_dump those arrays before foreach just to be clear how structure looks like.
Try something like this: (note also the counter++ is changed in $count++)
foreach ($pages[$page_number] as $key => $i) {
$count++;
if ($count == 5) {
echo '</tr><tr>';
echo '</div>';
echo '</div>';
$count = 0;
}
echo'<td>'.$i. " AND " . $addrs[$page_number][$key]
echo'</td>';
}

Foreach and columns

<?php
$arr = range(1,rand(40,120)); ?>
<table>
<?php
foreach ($arr as &$value) {
echo '<tr><td>' . $value . '</td></tr>';
} ?>
</table>
This generate for me for example:
1
2
3
...
111
all in one columns. How can i make - when in first column are 25 rows then create new column, etc. For example:
1 26 51
2 27 ...
3
..
25 50
How can i make it?
I can use DIV instead of table.
<?php
$arr = range(1,rand(40,120));
?>
<div style="width:40px; float:left;">
<?php
foreach ($arr as $value) {
echo $value . '<br />';
if ($value % 25 == 0) {
echo '</div><div style="width:40px; float:left;">';
}
}
?>
Vertically sorted columns of that sort (no pun intended) are a serious pain in html, since this arragement is a "top->bottom, left->right", while HTML tables by their nature are "left->right, top->bottom" instead.
To get around it, you have to do some offset math on the array indexes, so you can output by rows:
$arr = range(1,rand(40,120));
$rows = ceil(count($arr) / 3); // assuming 3 columns
for ($i = 0; $i < $rows; $i++) {
echo <<<EOL
<tr>
<td>{$arr[$i]}</td> 1, 2, 3, etc...
<td>{$arr[$i+rows]}</td> 11, 12, 13, etc...
<td>{$arr[$i+(2*$rows)]}</td> 21, 22, 23, etc...
</tr>
EOL;
}
This code probably won't work as is, but should give you the basic idea.
EDITED
<?php
$rows = 25;
$arr = range(1, rand(40, 120));
$arr = array_merge($arr, array_fill(0, $rows - (count($arr) % $rows), null));
$cols = ceil(count($arr) / $rows);
$render = array();
echo '<table>' . "\n";
foreach ($arr as $i => $value) {
$render[$i % $rows][] = $value;
if (count($render[$i % $rows]) == $cols) {
echo ' <tr>' . "\n" . ' <td>' . implode('</td>' . "\n" . ' <td>', $render[$i % $rows]) . '</td>' . "\n" . ' </tr>' . "\n";
}
}
echo '</table>' . "\n";
?>

Categories