PHP - Closing off a div with nested loops - php

I have a folder with around 400 images. I'd like to put them on a page put only eight at a time. Meaning i will have all the images on the same page, but cut in sections of eight images wrapped in a box like this:
<div class="eightbox">
<img src="image1">
<img src="image2">
<img src="image3">
<img src="image4">
<img src="image5">
<img src="image6">
<img src="image7">
<img src="image8">
</div>
<div class="eightbox">
<img src="image9">
<img src="image9">
<img src="image10">
<img src="image11">
<img src="image12">
<img src="image13">
<img src="image14">
<img src="image15">
</div>
Now my code for this so far makes an output, but does not close the "eightbox" so that every new div is inside the other one.
Here's my Code:
<?php
$files = glob("images/*.*"); //loads all the images from my folder into an array
$y = ceil(count($files)/8); // The amount of images divided by eight and rounded up
$z = 1; //This counter makes the array continue outside the loop
for ($i=1; $i<$y; $i++)
{
echo '<div class=\'eightbox\'>';
for ($q=0; $q<8; $q++)
{
$num = $files[$z];
echo '<img src=\'' . $num . '\' >';
$z++;
}
echo '</div>';
}
?>
I hope this makes any sense to you and thanks in advance for helping!
EDIT: on popular demand heres a screenshot of the code i'm getting with chrome:
Screenshot of my code

An alternative which splits the files into chunks of 8 ( using array_chunk()) and then outputs each chunk at a time...
$split = array_chunk($files, 8);
foreach ( $split as $div ) {
echo '<div class=\'eightbox\'>';
foreach ($div as $file ) {
echo '<img src=\'' . $file . '\' />';
}
echo '</div>';
}
Or using implode() to output the data...
$split = array_chunk($files, 8);
foreach ( $split as $div ) {
echo '<div class=\'eightbox\'><img src=\''.
implode('\' /><img src=\'', $div).
'\' /></div>';
}
which IMHO is a little less readable, but more compact.

Using Modulo you could do this
<?php
$files = glob("images/*.*"); //loads all the images from my folder into an array
foreach ( $files as $idx=>$file) {
if ( $idx % 8 == 0 && $idx != 0){ // every 8 close a div and open a new one
echo '</div>';
echo '<div class="eightbox">';
}
if ( $idx == 0 ){ // output first div
echo '<div class="eightbox">';
}
echo "<img src='$file'>";
}
if ( $idx+1 % 8 != 0 ) { // close the last div
echo '</div>';
}
?>

Related

Adding an incrementing prefix (html tag) and closing (html tag) suffix in a PHP foreach loop

I'm using a simple PHP foreach loop to display (in plain text) the url for each file (images in this case) found in a directory.
Here is the (working) code for that..
<?php
$directory = "imguploader/UploadFolder";
$images = glob($directory . "/*.png");
foreach($images as $image)
{
echo "http://www.myurl.com/".$image."<br />";
}
?>
Any this quite nicely almost does what I need, current results are like this..
http://www.myurl.co.uk/imguploader/UploadFolder/lp1-hot-pink.png
http://www.myurl.co.uk/imguploader/UploadFolder/lp2-green.png
http://www.myurl.co.uk/imguploader/UploadFolder/lp3-purple.png
But what I now need to do is add an (auto incrementing) html tag (as executing html, not txt)
eg <div id="img1">, <div id="img2">, <div id="img3"> etc to the start of each line, then the closing </div> tag to the end of each line the foreach creates.
Is this possible?
Try this:
<?php
$directory = "imguploader/UploadFolder";
$images = glob($directory . "/*.png");
$num = 0;
foreach($images as $image) {
$num++;
echo "<div id=\"img".$num."\">http://www.myurl.com/".$image."</div><br />";
}
?>
I've tested the above example and it works.
Use this code
<?php
$directory = "imguploader/UploadFolder";
$images = glob($directory . "/*.png");
$i = 0;
foreach($images as $image) {
$i++;
echo "<div id='img".$i."'>";
echo "http://www.myurl.com/".$image."<br />";
echo "</div>";
}
?>

How to loop through an array with mixed images and thumbnails?

I try to dynamically populate an HTML page with 2 images, the first a full image and the second a reduced image, but as I can not do AND with a foreach.
In fact, the code is ok, but I want populate my HTML with twos pics of the same folder; but this code bring back all pictures, it doesn't no the diff between the Full image and the Thumbnail.
The script bring back all picture. My folder contain images with specific titles:
Full Image = *.jpeg
Thumbnail = *_Low.jpeg
I would like to be able to modify my code to insert the full in the first line and the thumbnail in the second line.
<?php
$dir = './style/images/art/mairie/';
$files = scandir($dir);
$images = array();
array().sort();
$nb = 1;
foreach($files as $file) {
if(fnmatch('*.jpg',$file)) {
$images[] = $file;
}
}
var_dump($images);
foreach ($images as $image) {
echo '<div class="cbp-item">'.'<a class="cbp-caption fancybox-media" data-rel="portfolio" href="style/images/art/mairie/'.$image.'">'."\n"
.'<div class="cbp-caption-defaultWrap">'.'<img src="style/images/art/mairie/'.$image.'" alt="" /> </div>'."\n"
.'<div class="cbp-caption-activeWrap">'."\n"
.'<div class="cbp-l-caption-alignCenter">'."\n"
.'<div class="cbp-l-caption-body">'."\n"
.'<div class="cbp-l-caption-title"><span class="cbp-plus">'.'</span></div>'."\n"
.'</div>'."\n"
.'</div>'."\n"
.'</div>'."\n"
.'<!--/.cbp-caption-activeWrap --> '."\n"
.'</a> </div>'."\n";
}
?>
for the second line I would like to bring back the reduced photo, so to have
<div class="cbp-caption-defaultWrap"><img
src="style/images/art/mairie/Maurine_Tric-7399_Low.jpg" alt="" />
</div>
$images
Part of my $images array would look like this:
$images = [
"0" => "Maurine_Tric-7399.jpg",
"1" => "Maurine_Tric-7399_Low.jpg",
"2" => "Maurine_Tric-7407.jpg",
"3" => "Maurine_Tric-7407_Low.jpg",
"4" => "Maurine_Tric-7414.jpg",
"5" => "Maurine_Tric-7414_Low.jpg",
];
Desired Output
I'm trying to add one of the URLs in my array with large images, and the other with its thumbnail which are being differentiated with _Low:
<div class="cbp-item"><a class="cbp-caption fancybox-media" data-rel="portfolio" href="style/images/art/mairie/Maurine_Tric-7399.jpg"> <div class="cbp-caption-defaultWrap"><img src="style/images/art/mairie/Maurine_Tric-7399_Low.jpg" alt="" /> </div>
Just use preg_match() instead of fnmatch(), matching only the thumbail images and marking the part before _Low.jpg as Subpattern.
Then you can easily construct the filename of both images from that stub:
<?php
$dir = './style/images/art/mairie/';
$files = scandir($dir);
$images = array();
array().sort();
$matches = NULL;
foreach ($files as $file) {
if (preg_match('/^(.+)_Low\.jpg$/', $file, $matches)) {
$images[] = $matches[1];
}
}
foreach ($images as $image) {
echo '<div class="cbp-item"><a class="cbp-caption fancybox-media" data-rel="portfolio" href="' . $dir . $image . '.jpg"> <div class="cbp-caption-defaultWrap"><img src="' . $dir . $image . '_Low.jpg" alt="" /></div>';
}
?>
If we wish to just add one URL for our images and one for their thumbs in the foreach, we might be able to define a $html variable and step by step add to it, then we would finally echo that, and our code would look like something similar to:
<?php
$html = '<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document sans titre</title>
</head>
<body>';
$html .= '<ul>';
$dir = './style/images/art/mairie/';
$files = scandir($dir);
$images = array();
$nb = 1;
foreach ($files as $file) {
if (fnmatch('*.jpg', $file)) {
$images[] = $file;
}
}
foreach ($images as $key => $image) {
if ($key % 2 == 0) {
$html .= '<div class="cbp-item">
<a class="cbp-caption fancybox-media" data-rel="portfolio" href="style/images/art/mairie/' . $image . '">
<div class="cbp-caption-defaultWrap"><img src="style/images/art/mairie/' . $images[$key + 1] . '" alt="" /> </div>
<div class="cbp-caption-activeWrap">
<div class="cbp-l-caption-alignCenter">
<div class="cbp-l-caption-body">
<div class="cbp-l-caption-title"><span class="cbp-plus"></span></div>
</div>
</div>
</div>
</a>
</div>';
}
}
$html .= '</ul></body></html>';
echo $html;
Modifications
What we are modifying here is that we add an if to run every other time.
if ($key % 2 == 0) {
}
We add $key var in our foreach and finally we have two image links which we replace one of them with $images[$key+1], which one of them is for thumbs:
$image
$images[$key+1]

PHP Foreach loop if field is not empty

I am trying to master the art of the foreach loop; I have the following code which I am using with WordPress and the Advanced Custom Fields pluging. I want to turn it into a foreach loop.
<li data-thumb="<?php the_field('image_1'); ?>">
<img src="<?php the_field('image_1'); ?>" />
</li>
<li data-thumb="<?php the_field('image_2'); ?>">
<img src="<?php the_field('image_2'); ?>" />
</li>
<li data-thumb="<?php the_field('image_3'); ?>">
<img src="<?php the_field('image_3'); ?>" />
</li>
<li data-thumb="<?php the_field('image_4'); ?>">
<img src="<?php the_field('image_4'); ?>" />
</li>
<li data-thumb="<?php the_field('image_5'); ?>">
<img src="<?php the_field('image_5'); ?>" />
</li>
I have tried writing the code below but it doesn't work, and I don't know how to limit the loop to 5 (images). Note that get_field returns the image url whilst the_field returns the image.
<?php
$i=1;
foreach (!empty (get_field('property_image.$i.')) ) {
print (' <li data-thumb="<?php the_field('property_image'.$i.'); ?>">
<img src="<?php the_field('property_image'.$i.'); ?> ">
</li> ');
$i++;
}
?>
If you know that there are only 5 items, then you would just use a for or while loop. foreach is a loop designed for looping through an array of elements, which you don't have.
Consider this loop instead:
for($i = 1; $i <= 5; $i++) {
if( !empty(get_field('property_image'.$i)) ) {
echo '<li data-thumb="' . the_field('image_' . $i) . '">';
echo '<img src="' . the_field('image_' . $i) '" />';
echo '</li>';
}
}
foreach is used to iterate over arrays, e.g.
foreach (array_expression as $value) {
// current array element
}
The syntax you're using will not work with foreach (see examples to understand how it works).
For the implementation you posted, you would be better off using a normal for loop.
for ($i = 1; $i <= 5; $i++) {
// print <li>
}
To use a foreach loop, you need to have iterate over an array. get_field("name") does not return an array, however you CAN use foreach with get_fields()
$fields = get_fields();
if( $fields )
{
foreach( $fields as $field_name => $value )
{
// Output values here
}
}
Details here: http://www.advancedcustomfields.com/resources/get_fields/
In your case for loop is better as changed in the loop value is numeric. So solution will be like:
for ($i = 1; $i<=5; $i++) {
$src = the_field('image_'.$i);
printf('<li data-thumb="%s">', $src);
printf('<img src="%s" />', $src);
print('</li>');
}
If you still want to use foreach loop then you can use built-in php function range to get required numbers.
foreach (range(1, 5) as $i) {
$src = the_field('image_'.$i);
printf('<li data-thumb="%s">', $src);
printf('<img src="%s" />', $src);
print('</li>');
}
What you probably wanted to write was a while loop up there. Foreach loops don't test a condition before a cycle. Rather, foreach loops take an array and iterate over all the values within. It can also iterate over associative arrays.
<?php
$users = array(
'user_mango' => 'John Doe',
'user_2' => 'Jacob Doe',
'user_potato' => 'Jane Doe'
);
foreach ($users as $user_id => $name) {
echo $user_id, ' - ', $name, '<br>';
}
should output
user_mango - John Doe
user_2 - Jacob Doe
user_potato - Jane Doe
I'm not a wordpress developper but if you wanted to write this code in the style you started off with, here goes:
<?php
$i = 0;
while (!empty(get_field('property_image.$i.')) && $i < 5) {
echo 'YOUR TEMPLATE CODE';
$i++;
}
while loops, unlike foreach loops, test a condition before each iteration. Here in the above example code, we have our counter variable initialized to zero. Inside the loop we increase the counter variable by one on each iteration, and in the condition, we specify that in order for the full expression to be true the counter must be smaller than 5.

Add <br /> after every set of 5 images

Okay, I am currently using this:
<?php
$dirname = "cards/collecting/";
$images = glob($dirname."*.png");
foreach ($images as $image) {
$title = pathinfo($image);
echo '<img class="deck" src="'.$image.'" alt="'. $title['filename'].'" title="'.$title['filename'].'">';
}
?>
This pulls a bunch of small images out of a folder and displays them. It works great, but I want there to be a after each 5th image, so it doesn't stretch across the entire div in which the image are being shown. I'm unsure what I need to add to do this.
Thanks in advance!
Using the index, you can write <br/> every time the index+1 is a multiple of 5: index 4, 9, 14, etc... Notice that I use $i=> in the foreach to get the value of $i.
<?php
$dirname = "cards/collecting/";
$images = glob($dirname."*.png");
foreach ($images as $i=>$image) {
$title = pathinfo($image);
echo '<img class="deck" src="'.$image.'" alt="'. $title['filename'].'" title="'.$title['filename'].'">';
if(($i+1)%5 == 0) echo '<br/>';
}
?>
The easiest way is use array_chunk.
array_chunk
array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )
Chunks an array into arrays with size elements. The last chunk may contain less than size elements
Code example:
$dirname = "cards/collecting/";
$images = glob($dirname."*.png");
$grp = array_chunk($images, 5, true);
foreach ($grp as $items) {
echo '<div class="item_grp">';
foreach ($items as $image) {
$title = pathinfo($image);
echo '<img class="deck" src="'.$image.'" alt="'. $title['filename'].'" title="'.$title['filename'].'">';
}
echo '</div>';
}

How to format a table to display images in PHP

I have images in an array and I want them to be display in a table with 3 columns!
So obviously in HTML, it is like:
<table>
<tr>
<td><img src="image1.jpg"></td>
<td><img src="image2.jpg"></td>
<td><img src="image3.jpg"></td>
</tr>
<!-- and so on... -->
</table>
So I want it to print out in PHP but the problem is the code.
My code is like this:
$photos = array( "image1",
"image2",
"image3",
"image4",
"image5",
);
foreach ($photos as $photo) {
$i = 0;
if ($i < 3) {
echo '<td><center><img src="'.$photo.'.jpg"></td>';
$i++;
} elseif ($i == 3) {
echo '</tr><tr>';
$i = 0;
}
}
I don't know what seems to be the problem and every time I echo out the variable $i, it echoes out like 11111111111111111111111111111111111111111111.
change this
foreach ($photos as $photo) {
$i = 0;
to
$i = 0;
foreach ($photos as $photo) {
Why is $i inside the foreach loop? That must be the reason. The $i gets initialized at the start of each loop cycle.
Try display:inline-block; instead in css. This works very well.
Here's an example...
<img src="image1.jpg" style="display:inline-block;>
<img src="image2.jpg" style="display:inline-block;>
<img src="image3.jpg" style="display:inline-block;>
You can even ask if you want to add text or something with the images...
I find using array_chunk for this kind of thing is more elegant.
$chunks = array_chunk($photos, 3);
foreach ($chunks as $chunk)
{
echo '<tr>';
foreach ($chunk as $photo)
{
echo '<td><img src="', $photo, '.jpg" /></td>';
}
echo '</tr>';
}
Also, don't use the 'center' tag, it is deprecated. Use CSS to align content.
Also, strictly speaking, this is not what HTML tables are for. Sure they work well. Actually, they work better than the 'proper' solution but they are not correct. Still, go ahead and use them if you just need a quick fix. It doesn't actually cause any problem to do so.

Categories