PHP foreach loop that creates four colums on flexbox - php

I'm trying to make something like a flexbox with CSS and PHP. The idea is to upload .jpg images to a folder and then sort them into four columns equally. My current approach is to count the total number of files in the folder, divide by four and with that create indices for a foreach loop to iterate and put the images into the columns. I need it to look like this.
Later on I'll have to make a popup on each of these images which should bring some basic HTML/CSS thing. Not sure if that's something to take in mind for this particular case.
This is my (incomplete/not working) code:
<?php
$fi = new FilesystemIterator("../../showoff_images", FilesystemIterator::SKIP_DOTS);
printf("There were %d Files", iterator_count($fi));
$fi = iterator_count($fi);
#Divided $f1 by four to get the number of items in columns
$fby4 = intdiv($fi,4);
#Create start index for each image
$f0 = 0;
$f1 = $fby4-1;
$f2 = $fby4*2-1;
$f3 = $fby4*3-1;
$f4 = $fby4*4-1;
#CHECK THE INDEX FOR THE IMAGES. START AT 0 AND START ITERATING WITH THE $fn VALUES FOR THE FOLLOWING FUNCTION!
#Iterates images
$directory="../../showoff_images/";
$images=glob($directory . "*.jpg");
$lazyload = "lazy";
$measure = "100%";
$distance = "20px";
foreach($images as $image=>$value) {
if($value > 4) continue;
++$value;
echo
"
<h2 style = padding-top= ".$distance." padding-bottom= ".$distance." padding-right= ".$distance." padding-left= ".$distance."></h2>
<img src=" .$image." loading =". $lazyload ." height=".$measure." width=".$measure.">
";
#++$f0;
}
?>
Really appreciate your help and glad to be joining the forum!

Comment to answer
You should be able to use array_chunk for this, which will allow you to break your array up into sub-arrays.
Here's a sample, not really bound to your data but it should make sense.
$letters = range('a', 'z');
$rows = array_chunk($letters, 4);
foreach($rows as $row){
echo '<div>', PHP_EOL;
foreach($row as $letter) {
echo $letter, PHP_EOL;
}
echo '</div>', PHP_EOL;
}
Demo here: https://3v4l.org/HpTSH

Related

Remove the 0 from for results

Currently, I'm messing around with SoundCloud's API and it's returning something that looks like this.
0. HotBox Michael da Vinci Prod Free P.mp3
https://api.soundcloud.com/tracks/373337717/stream?client_id=OURID
1. LSSR Chris P Prod Jake Knight.mp3
https://api.soundcloud.com/tracks/373336760/stream?client_id=OURID
Which is working properly as how the code appears, here it is how I'm printing out the results (very messy but I'm just messing around)
for ($i = 0; isset($house[$i]); $i++) {
$b1 = $house[$i]['title'];
$b2 = $house[$i]['stream_url'];
print '<br>'; print '<br>';
$title = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($b1));
print ''.$i.'. '.$title.'.mp3';
print '<br>';
print $stream = ''.$b2.'?client_id=OURID';
}
Now what I'm wondering is how under every circumstance can we make the 0. return as a 1. and continue counting upwards until reaching the end of the for loop, not removing the 0. data but only changing the number.
I recommend a foreach loop with the $i counter declared in the loop and just increment it as you go.
Untested code:
foreach ($house as $i=>$row){
echo '<br><br>',++$i,'. ',preg_replace ('/[^a-z\d\s]+/i','',strip_tags ($row ['title'])),".mp3<br>{$row ['stream_url']}?client_id=OURID";
}
p.s. I've improved the regex pattern and eliminated all single-use variable declarations. You can break this up over many lines if you prefer.
If you want to avoid the first iteration's double break tags...
foreach ($house as $i=>$row){
if($i) echo '<br><br>'; // if $i is not 0
echo ++$i,'. ';
echo preg_replace ('/[^a-z\d\s]+/i','',strip_tags ($row ['title']));
echo ".mp3<br>{$row ['stream_url']}?client_id=OURID";
}
Based on the comments and your description of what you are trying to do, it sounds like you just need to add another iteration variable:
# Add another variable
$a = 1;
for ($i = 0; isset($house[$i]); $i++) {
$b1 = $house[$i]['title'];
$b2 = $house[$i]['stream_url'];
$title = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($b1));
echo '<br><br>';
# Here you have the $a show up starting at 1
echo ''.$a.'. '.$title.'.mp3<br>';
echo $stream = ''.$b2.'?client_id=OURID';
# Auto increment here
$a++;
}

How to read filenames containing a number and only use those with less than or equal to a specified value, also how to make my 'cache' more efficient?

So I've got a couple of questions that I'm hoping someone will be able to help me with.
Firstly, I'm trying to create a page which parses information and organizes it by the hour into a table. At the moment my script parses the information with Simple HTML Dom and creates a text file for each hour called "hour_%time%.txt" (e.g. hour_02.txt, hour_14.txt, hour_22.txt). Each file will contain the parsed information as a table row.
How would I go about only using the files with times earlier than the current hour, so if the current hour was 9am, only files ending with equal to or less than 09 would be used? I was trying to use either explode or preg_match but I couldn't get it to work.
My code at the moment looks like so:
date_default_timezone_set('UTC');
$currentHour = date('H');
$cache_file = 'cache/hour_'.$currentHour.'.txt';
$data = '<tr><td>'.date('H:00').'</td><td>'.$firmato_count.'</td><td>'.$inviato_count.'</td><td>'.$positive_count.'</td><td>'.$negative_count.'</td></tr>';
file_put_contents($cache_file, $data);
echo '<table class="table"><tbody>';
echo '<tr><th>Time</th><th>Firmato</th><th>Inviato</th><th>Positive</th><th>Negative</th></tr>';
$files = glob("cache/hour_*.txt");
foreach($files as $txt){
$hourlyfile = file_get_contents($txt);
echo $hourlyfile;
}
echo '</table></tbody>';
And secondly, I'm fully aware this isn't the best way to do this but I couldn't figure out a better way myself. Can anyone suggest a more efficient way to store the parsed data and access it? Is it possible to use a single file? I did consider appending the same file however as my page will update frequently it ended up adding multiple lines of data for the same hour. Each file contains a string like so:
<tr><td>10:00</td><td>21</td><td>58</td><td>4</td><td>43</td></tr>
Any help is appreciated.
First convert your String of the hour to a number
[PHP]
$currentHour = intval($currentHour);
next compare
if($currentHour <= 9){ // < for less and <= for less and equal
doStuff
}
This only will display the file of the exact hour. Tell me if doesn't work for edit it.
date_default_timezone_set('UTC');
$currentHour = intval(date('H'));
$cache_file = 'cache/hour_'.$currentHour.'.txt';
$data = '<tr><td>'.date('H:00').'</td><td>'.$firmato_count.'</td><td>'.$inviato_count.'</td><td>'.$positive_count.'</td><td>'.$negative_count.'</td></tr>';
file_put_contents($cache_file, $data);
echo '<table class="table"><tbody>';
echo '<tr><th>Time</th><th>Firmato</th><th>Inviato</th><th>Positive</th><th>Negative</th></tr>';
$files = glob("cache/hour_*.txt");
if($currentHour == $currentHour){
foreach($files as $txt){
$hourlyfile = file_get_contents($txt);
echo $hourlyfile;
}
}
echo '</table></tbody>';
I ended up creating a variable called $globSearch and used if/elseif to create a search string based on the current hour. My code now looks like this:
date_default_timezone_set('UTC');
$currentDate = date('d/m/Y');
$currentHour = intval(date('H'));
$cache_file = 'cache/hour_'.$currentHour.'.txt';
$data = '<tr><td>'.date('H:00').'</td><td>'.$firmato_count.'</td><td>'.$inviato_count.'</td><td>'.$positive_count.'</td><td>'.$negative_count.'</td></tr>';
file_put_contents($cache_file, $data);
echo '<table class="table"><tbody>';
echo '<tr><th>Time</th><th>Firmato</th><th>Inviato</th><th>Positive</th><th>Negative</th></tr>';
if ($currentHour <= 9) {
$globSearch = "{cache/hour_[0][0-".$currentHour."].txt}";
} elseif ($currentHour >= 10 && $currentHour <= 19) {
$splitInt = str_split($currentHour);
$globSearch = "{cache/hour_[0][0-9].txt,cache/hour_[1][0-".$splitInt[1]."].txt}";
} elseif ($currentHour >= 20 && $currentHout <= 23) {
$splitInt = str_split($currentHour);
$globSearch = "{cache/hour_[0][0-9].txt,cache/hour_[1][0-9][2-".$splitInt[1]."].txt}";
}
//$files = glob("{cache/hour_[0][0-9].txt,cache/hour_[1][0-3].txt}", GLOB_BRACE);
$files = glob($globSearch, GLOB_BRACE);
foreach ($files as $txt) {
$hourlyfile = file_get_contents($txt);
echo $hourlyfile;
}
echo '</table></tbody>';
Thanks for replying Ruben and COOLGAMETUBE, much appreciated.

More elegant solution to this nested loop, anyone?

I have a php procedure that scans a directory where its content is thumbnail images of pdf files. The thumbnails are then displayed in a table, and included in an iframe of a parent web page. Each thumbnail is itself a hyperlink when clicked will open the actual pdf file. To avoid having a horizontal scroll bar, 9 images in a table row is perfect. I wrote a nested loop that in effect acts like a word wrap, where it displays 9 images and then begins another row. The actual code is much more entailed, so I have it pared down to a bare minimum example. It seems almost counter intuitive on first glance, decrementing $i on the second line of the outer loop, but it works. I wonder if anyone has a more elegant solution?
$ary = array(1,2,3,4,5,6,7,8,9,10);
for ($i=1; $i<(count($ary)+1); $i++) {
$i = $i-1;
for($j=0; $j<9; $j++) {
if ($i === count($ary)) break;
echo ($ary[$i].", ");
$i+=1;
}
echo "<br>";
}
The completed code now where $ndx is the count of the array, $dir is the scanned directory containing the png images, and $rtDir is the directory where the pdf's are saved:
if ($ndx > 0) {
$tbl = '<div id="draggable" class="ui-widget-content">
<ul>
<table><tr>';
/* place 9 images on one row */
foreach ($myfiles as $index => $image) {
$pdf = basename($image, ".png");
$pdf = $pdf . ".pdf";
$pdf = $rtDir.$pdf;
$tbl .= '<td>
<span class="zoom">
<a href="'.$pdf.'" target="_blank">
<li><img id="pdfthumb'.$index.'" class="myPhotos" alt="pdf'.$index.'" src="'.$dir.$image.'" ></li>
</a>
</span>
</td>';
if ($index % 9 == 8) {
/* end the current row and start a new one */
$tbl.= "</tr></table><br><br><table style='margin-top:-40px'><tr>";
}
}
$tbl .= "</tr></table></ul></div>";
printf($tbl);
unset($myfiles);
}
Thanks everyone for your suggestions.
So you want 9 images on each row? There are usually two logical choices:
Alternative 1: You use array_chunk(), e.g. like this:
$chunks = array_chunk($images, 9);
foreach ($chunks as $chunk) {
foreach ($chunk as $image) {
// image printing goes here
}
echo '<br'>;
}
Alternative 2: You use the modulo operator, e.g. like this:
foreach ($images as $index => $image) {
// images printing goes here
if ($index % 9 == 0) { // or 8, since it's a 0-index array... I don't remember
echo '<br>';
}
}
I mostly use the second version, myself, if I have to - or I ask one of our designers to make it fit to a proper width through css. Do note also that the second version won't work if your images array is associative.
$b = count( $ary ) - 1 ;
for( $i = 0 ; $i <= $b ; $i++ ) :
echo $ary[$i] ;
if( ( $i + 1 ) % 9 == 0 ) :
echo "<br>" ;
endif ;
endfor ;
like the above comment i like modulus but i also prefer the for loop, hope this helps.

Display images from directory?

I have a code to display images from folder which is working fine but in Google chrome it's showing one extra box like image.How I can fix this ?
Here is my code:
<?php
$files = glob("photogallery/thumb/group1/*.jpg*");
for ($i=0; $i<=count($files); $i++)
{
$num = $files[$i];
echo '<img src="'.$num.'" width="100px" height="100px" alt="">'." ";
}
?>
The problem is that count() is going to return the total number of items in your zero-indexed array. That means if your $files array has 10 items in it, the lowest index is 0 and the highest index is 9.
Your comparison of $i<=count($files) means that $i would go from 0 to 10 (11 total items) in this example.
I recommend using foreach anyway. It's a more generic way of iterating over a collection, and allows for sparse arrays.
foreach ($files as $file) {
// use the $file variable here in your echo
}
<?php
$files = glob("photogallery/thumb/group1/*.jpg*");
for ($i=0; $i<=count($files); $i++)
{
if(trim($files[$i])){
$num = $files[$i];
echo '<img src="'.$num.'" width="100px" height="100px" alt="">'." ";
}
}
?>

how to generate a random image output

i have some basic php code that pulls an image from a particular image folder when the user asks using a form.
I will have many image folders and want to generate a random image instead of using
case 'A' : echo "<a href=\"Alphabet-Letters/Letters-A\">
<img src=\"image/data/A/A_001.jpg\" id=\"A1\" width=\"70\" height=\"120\" title=\"A1\"/> </a>" ; break;
My question is this as the form is processed with someone using the letter A the picture of that letter appears. The php code for this is
if (array_key_exists('check_submit', $_POST))
{
$letters = $_POST['Comments'];
$num_letters = strlen($letters);
for($i = 0; $i < $num_letters; $i++)
{
switch ($letters[$i]) {
case 'A' : echo "<a href=\"Alphabet-Letters/Letters-A\">
<img src=\"image/data/A/A_001.jpg\" id=\"A1\" width=\"70\" height=\"120\" title=\"A1\" alt=\"Image A\"/>
</a>" ;
break;
This only pulls the exact image i have asked, but i have hundreds in that folder and would like a more simple code to work with.
Please can someone help, they gave advise on using random image from folder, but that only works as a starting point not on the code I already have.
Thanks for your time
The solution posted at the link below should achieve the functionality you are looking for.
https://stackoverflow.com/a/4478788/1152375
so you should be able to do something like
case 'A' : echo "<a href=\"Alphabet-Letters/Letters-A\">
<img src=\"image/data/A/" . random_pic("folder_with_pics") . "\" id=\"A1\" width=\"70\" height=\"120\" title=\"A1\</a>";
break;
before you get to the output code, you will want to get a list of all files in the relevent directory ( http://php.net/manual/en/function.dir.php ) in a numbered array.
count the number of items in the array ( http://php.net/manual/en/function.count.php ) and randomly pick one ( http://php.net/manual/en/function.rand.php ) using the min and max settings of rand.
Try using the scandir function to find all the files in the folder, and then use the rand function to randomly choose one:
if(!empty($_POST['check_submit']))
{
$letters = strtoupper(trim($_POST['Comments']));
$num_letters = strlen($letters);
for($i = 0; $i < $num_letters; $i++)
{
$letter = $letters[$i];
$folder = 'image/data/'.$letter;
$files = scandir($folder);
array_shift($files);
array_shift($files);
$index = rand(0, count($files) - 1);
$file = $files[$index];
echo "<a href=\"Alphabet-Letters/Letters-{$letter}\">\n";
echo "<img src=\"image/data/{$letter}/{$file}\" id=\"{$letter}{$index}\" width=\"70\" height=\"120\" title=\"{$letter}{$index}\" alt=\"Image {$letter}\"/>\n";
echo "</a>\n";
}
}
Found the answer by using #Buchow_php and trial and error.
for ($i=0; $i<$num_letters; $i++)
{
$image_num = '$image'.$i;
echo "<input type=\"hidden\" name=\"option[$image_num]\" value=\"$skus[$i]\" />";
}
together with the previous code and now it brings all the image files into an array for posting to my submit

Categories