foreach inside foreach issue - php

I have two directories : one has images and the other has ZIP files.
The files in both directories have the same names e.g : 1.zip , 1.png
I scanned each folder like this :
$images = 'screenshots/';
$scanned_images = array_diff(scandir($images), array('..', '.'));
$zips = 'download/';
$scanned_zips = array_diff(scandir($zips), array('..', '.'));
then :
foreach ($scanned_images as $value)
{
echo '<div class="portfolioItem">';
echo '<a href="screenshots/'.$value.'" class="zoom img" title="'.$value.'" rel="portfolio">';
echo '<img src="screenshots/'.$value.'" class="portfolio-image" alt="'.$value.'" /> </a>';
foreach ($scanned_zips as $val)
{
echo '<div class="portfolioDescription">';
echo'<h4>Download:'.$val.'</h4>';
echo'<p>Click here to download</p>';
echo'</div></div>';
}
}
This does not work. Each image in first directory will have the whole zip files of second directory in its description!
I have also tried to combine the two arrays into one array and use foreach ($result as list ($a, $b)) but as list always gives an error.
How to overcome this ?

no need to have nested foreach.
use this:
<?php
$images = 'screenshots/';
$scanned_images = array_diff(scandir($images), array('..', '.'));
$zips = 'download/';
$scanned_zips = array_diff(scandir($zips), array('..', '.'));
foreach ($scanned_images as $value)
{
$name = substr($value, 0, strrpos($value, '.'));
$pos = array_search($name.'.zip', $scanned_zips);
if($pos != null){
echo '<div class="portfolioItem">';
echo '<a href="'.$images.$value.'" class="zoom img" title="'.$value.'" rel="portfolio">';
echo '<img src="'.$images.$value.'" class="portfolio-image" alt="'.$value.'" />';
echo '</a>';
echo '<div class="portfolioDescription">';
echo '<h4>Download:'.$scanned_zips[$pos].'</h4>';
echo '<p>Click here to download</p>';
echo '</div>';
echo '</div>';
}
}

Add a break; statement at the end of your inner foreach loop and that should fix it. You have two foreach loops and hence the downloads are listed multiple times. To fix this issue,
Change your code to:
<?php
foreach ($scanned_images as $value)
{
echo '<div class="portfolioItem">';
echo '<a href="screenshots/'.$value.'" class="zoom img" title="'.$value.'" rel="portfolio">';
echo '<img src="screenshots/'.$value.'" class="portfolio-image" alt="'.$value.'" /> </a>';
foreach ($scanned_zips as $val)
{
echo '<div class="portfolioDescription">';
echo'<h4>Download:'.$val.'</h4>';
echo'<p>Click here to download</p>';
echo'</div></div>';
break; //exiting
}
}
?>

One way is to hash your files by name without extension. Then use same key to retrieve image data and zip data. Example:
$scanned_images = array('1.png', '2.png');
$scanned_zips = array('1.zip', '2.zip');
//Should be like that after hashing
$scanned_images = array('1' => '1.png', '2' => '2.png');
$scanned_zips = array('1' => '1.zip', '2' => '2.zip');
So the code could be:
function get_file_name($path) {
$name = basename($path);
$name = substr($name, 0, strrpos($name, '.'));
return $name;
}
function hash_files_by_name($items) {
$hashed = array();
foreach($items as $item) {
$name = get_file_name($item);
$hashed[$name] = $item;
}
return $hashed;
}
$scanned_images = array('1.png', '2.png'); // get images directory filesnames
$scanned_zips = array('1.zip', '2.zip'); // get zips directory filenames.
$imgs = hash_files_by_name($scanned_images);
$zips = hash_files_by_name($scanned_zips);
foreach ($imgs as $key=>$value)
{
echo '<div class="portfolioItem">';
echo '<a href="screenshots/'.$value.'" class="zoom img" title="'.$value.'" rel="portfolio">';
echo '<img src="screenshots/'.$value.'" class="portfolio-image" alt="'.$value.'" /> </a>';
if(isset($zips[$key])) {
echo '<div class="portfolioDescription">';
echo'<h4>Download:'.$zips[$key].'</h4>';
echo'<p>Click here to download</p>';
echo'</div></div>';
}
}

Related

Get all img and pdf with php

I'm trying to get all images from folder with php and link them with another folder where I have pdf files. The names of both are the same.
My code looks like this:
$dir_jpg = "../wp-content/uploads/newspaper/jpg/";
$dir_pdf = "../wp-content/uploads/newspaper/pdf/";
$images = glob($dir_jpg."*.*");
$pdfs = glob($dir_pdf."*.*");
$array = array_combine($images, $pdfs);
foreach($array as $image => $pdf){
echo '<ul>';
echo '<li>';
echo '<img src="'.$image.'" height="100" width="100" />';
echo '</li>';
echo '</ul>';
}
I did var_dump to check the array, but it was empty. What could be the reason my code is not working?
Update
I store my files in a wordpress folder system, but I didn't upload them through
wordpress media, so there is no records about them in database. I want to avoid it, and upload those files through ftp account and list them with a php code.
Update 2 On chat with #Gabor Klement we have got to this
$wp_root = wp_upload_dir()['baseurl'];
$dir_jpg = $wp_root."/newspaper/jpg/";
$dir_pdf = $wp_root."/newspaper/pdf/";
$images = glob($dir_jpg."*.*");
$pdfs = array();
$imgNum = count($images);
$list = '<ul>';
for ($i = 0; $i < $imgNum; $i++) {
$filename = substr(basename($images[$i]), 0, -4);
$pdfs[$i] = $dir_pdf.$filename.".pdf";
if (file_exists($dir_pdf.$filename.".pdf")) {
$list .= '<li><img src="'.$images[$i].'" height="100" width="100" /></li>';
}
}
$list .= '</ul>';
echo $list;
but for some reason wordpress is not showing those files. Funy part is that <img src="<?php echo $dir_jpg ?>/july2012.jpg" /> placed before the $list works
Update 3
the only thing that is passing paths to $images is wp_upload_dir()['basedir']; but then the wordpress creates a path like this domain.com/home/user/domains/domain/public_html/wp-content/uploads/newspaper/jpg/december2012.jpg and the image is not found.
I found a solution for my problem. I had to use wp_upload_dir()['basedir'] to pass the path to glob, and then wp_upload_dir()['baseurl']to pass the link to src.
Maybe it not the best solution, but it works.
$base_dir = trailingslashit(wp_upload_dir()['basedir']);
$base_url = wp_upload_dir()['baseurl'];
$dir_jpg = '/newspaper/jpg/';
$dir_pdf = '/newspaper/pdf/';
$images = glob($base_dir.$dir_jpg.'*.*');
foreach($images as $image) {
$url = $base_url.$dir_jpg.basename($image);
$filename = substr(basename($image), 0, -4);
$pdfs = $base_url.$dir_pdf.$filename.".pdf";
printf('<img src="%s" alt="'.$filename.'.pdf"><div class="newspaper-hover"></div>', esc_url($url));
}

How to display all images if they exist in a folder PHP?

I have a PHP script that scans a specified Movie directory then displays it styled on a webpage using for loop and php. The code is below. I tried using glob but once I have all the images in an array how do I compare them to the array with all of the movies then if the image and the movie folder match to display the image with the correct name?
<?php
// set dir to the directiry you want to index
$dir = 'Movies/';
// scanning the directory you set
$scan = scandir($dir);
// I have this value at 11 because the first movie shows up
// in the 11th file in the array
$file = 11;
// This then removes the first useless files from our array
$scanned = array_slice($scan, $file);
// gets the amount of files
$FileNum = count($scanned);
// display all images and fanart
$images = glob('*.jpg');
// for loop that goes through the array
for ($i = 0; $i <= $FileNum; $i++) {
// gives the class for styling
echo '<li class="image">';
this is problem bit
// check if there is fanart/images in the folders
if (file_exists($dir . $scanned[$i] . $images)) {
// if there is images display them styled
echo '<img id="box1" src="' . $dir . $scanned[$i] . '*.jpg' . '" width="280" height="150" />';
} else {
// if not then display default image
echo '<img id="box1" src="http://placehold.it/280x150" width="280" height="150" />';
}
// make the box clickable to where the folder is located
echo '<a href="'. $dir . $scanned[$i] .'">';
// display the name of the movie and some JS
echo '<span class="text-content"><span>' . $scanned[$i] .'<br><br><i class="fa fa-4x fa-play-circle-o"></i><br><br><i class="fa fa-chevron-down" onclick="openNav()" aria-hidden="true"></i></span></span> </a>';
}
The file structure is as follows
`MOVIES---
\--random movies
\--mp4 and .jpg files`
To clarify my question is - Is there a way to check if a file exists, and if it does then put it in an array? I've tried using glob but that can't check if the file exists.
Well there is an * in your echo i don't think it needs to be there.
And if your movie directory gets updated, or the images. Then your script does not work anymore. Because of the hard slicing (11th file).
Maybe this will work for you:
<?php
// movies
$dir = "movies/";
$files = scandir($dir);
$movies = array();
$images = array();
foreach ($files as $file) {
// check for the mime type:
$mime = mime_content_type($dir . $file);
$type = substr($mime, 0,5);
$filename = pathinfo($dir . $file, PATHINFO_FILENAME);
if ($type == "video") $movies[] = $file;
if ($type == "image") $images[] = $filename;
}
foreach ($movies as $movie) {
$placeholder = true;
foreach($images as $image) {
if (strpos($movie, $image) !== false) {
$placeholder = false;
continue;
}
}
if ($placeholder) {
echo $movie . " - placeholder<br>";
} else {
echo $movie . " - image<br>";
}
}
It works with the mime-type.

Display a multi image(array) name from database in codeigniter

My problem is how to display the array image from database. I called that array image because when I uploaded that image I'm using an array to do upload to database.
I'm using this code to insert the file name to database
public function multipost()
{
$filepath = $this->upload->get_multi_upload_data('file_name');
$filenames = '';
foreach($filepath as $a) {
$filenames .= $a['file_name'].",";
}
$filenames = rtrim($filenames,',');
$db_data = array(
'pic_id'=> NULL,
'ad_pic'=> $filenames,
);
$this->db->insert('technical_slide_img', $db_data);
}
That result to
As you can see the ad_pic column has the value of 1.jpg,2.jpg.
if I'm using like this
<?php foreach ($this->header_model->getalldata() as $row) {
$image_arr = explode("/", $row->image);
$image_name = end($image_arr);
echo base_url().'images/'.$image_name;
} ?>
to display that image. Is there any way to display that images? Or do I need to separate that 2 images into row?
replace
<?php foreach ($this->header_model->getalldata() as $row) {
$image_arr = explode("/", $row->image);
$image_name = end($image_arr);
echo base_url().'images/'.$image_name;
} ?>
with
<?php
foreach ($this->header_model->getalldata() as $row)
{
$image_arr = explode(",", $row->ad_pic);
foreach($image_arr as $image_name)
{
echo base_url().'images/'.$image_name .'<br />';
}
}
?>
As i see in your database table image is saved with comma , and you are exploding it with slash / . So i think you have to replace / with , in your explode function.
<?php foreach ($this->header_model->getalldata() as $row) {
$image_arr = explode(",", $row->image);
$image_name = end($image_arr);
echo base_url().'images/'.$image_name;
} ?>
<?php
$image_arr = explode(",", $data_user->image);
foreach($image_arr as $image_name)
{?>
<img style="width:5em;"src="<?php echo base_url().'uploads/'.$image_name?>" class="img-reponsive thumbnail">
<!-- echo base_url().'images/'.$image_name .'<br />'; -->
<?php }
?>

php foreach how to filter image names to display certain images you want

Files are
AAA_1.jpg AAA_2.jpg AAA_3.jpg BBB_1.jpg BBB_2.jpg CCC_1.jpg
foreach ($carousel as $image) {
echo "<img src='images/$image'>";
}
How to filter image names, just to display AAA_ images.
result to see
<img src='images/AAA_1.jpg'>
<img src='images/AAA_2.jpg'>
<img src='images/AAA_3.jpg'>
There are a probalby a million ways to do this, but I would just check the name of the image to see it begins with 'AAA_'
foreach ($carousel as $image) {
if(strpos($image,'AAA_') === 0){
echo "<img src='images/carousel/$image'>";
}
}
Or more complex, but still fun, entertainingly worth the extra performance hit of explode:
foreach ($carousel as $image) {
$image_parts = explode('_', $image);
if($image_parts[0] == 'AAA'){
echo "<img src='images/carousel/$image'>";
}
}
foreach ($carousel as $image) {
if(substr($image, 0, 3) == 'AAA'( {
echo "<img src='images/carousel/$image'>";
}
}
If you know all your file, you can use that code, also use in_array ;-)
$carousel = array('AAA_1.jpg', 'AAA_2.jpg', 'AAA_3.jpg','BBB_1.jpg','BBB_2.jpg','CCC_1.jpg');
$entry = array('AAA_1.jpg', 'AAA_2.jpg', 'AAA_3.jpg');
foreach ($carousel as $image) {
if(in_array($image, $entry)) {
echo "<img src='images/carousel/$image'>";
}
}
By using substr and strlen you will be able to get the images you want starting with the prefix variables value.
$prefix = 'AAA_';
$carousel = array(
"AAA_1.jpg",
"AAA_2.jpg",
"AAA_3.jpg",
"BBB_1.jpg",
"BBB_2.jpg",
"CCC_1.jpg"
);
foreach ($carousel as $k => $v) {
if (substr($v, 0, strlen($prefix)) == $prefix) {
echo "<img src=\"images/{$v}\" alt=\"image {$k}\" />";
}
}

Echo php array value

I have the following code that reads the content of a folder
PHP Code:
<?
//PHP SCRIPT: getimages.php
header('content-type: application/x-javascript');
//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnimages($dirname="./images") {
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";' . "\n";
$curimage++;
}
}
closedir($handle);
}
sort($files);
return($files);
}
echo 'var galleryarray=new Array();' . "\n"; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
which spits out this the following code:
var galleryarray = new Array();
galleryarray[0] = "image1.jpg";
galleryarray[1] = "image5.jpg";
galleryarray[2] = "image2.jpg";
galleryarray[3] = "image4.jpg";
galleryarray[4] = "image8.jpg";
galleryarray[5] = "image7.jpg";
galleryarray[6] = "image0.jpg";
galleryarray[7] = "image3.jpg";
galleryarray[8] = "image6.jpg";​
Now in my html file I want to echo something like
<img src="images/image0.jpg" />
<img src="images/image1.jpg"/>
...
...
How can I do that?
foreach($galleryarray as $img) {
echo "<img src='images/$img' />";
}
maybe this help u
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
if($handle = opendir("./images")) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ ?>
<img src="/images/<?php echo $file; ?>">
<?php
}
}
}
assuming that you want to sort image name by value and then show the images. you first need to sort values by using function "asort"
asort($galleryarray);
foreach ($galleryarray as $key => $val) {
echo "<img src='images/{$val}'/>"
}
if you want to print and array
1) print_r($array); or if you want nicely formatted array then
echo '<pre>'; print_r($array); echo '<pre/>';
2) use var_dump($array) to get more information of the content in the array like datatype and length.
3) you can loop the array using php's foreach(); and get the desired output. more info on foreach in php's documentation website http://in3.php.net/manual/en/control-structures.foreach.php
Try changing the echo line in the function to this:
echo '<img src="images/' . $file . '" />' ;
Hope this will help :)
OR
Outside the function, use it like this:
$images = returnimages(); //will get the array containing the images
foreach($images as $img)
{
echo '<img src="images/' . $img . '" />';
}
Also, you have to include this line inside the if condition in the while loop:
$files[] = $file; //insert the file into the array. This array is what we are going to return from the function
Update
I have tested this code and it's working:
//PHP SCRIPT: getimages.php
header('content-type: application/x-javascript');
function returnimages($dirname="./images") {
$pattern="([^\s]+(\.(?i)(jpg|png|gif|bmp))$)"; // http://www.mkyong.com/regular-expressions/how-to-validate-image-file-extension-with-regular-expression/
$files = array();
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(preg_match($pattern, $file)){ //if this file is a valid image
$files[] = $file;
}
}
closedir($handle);
}
//sort($files); // http://php.net/manual/en/function.sort.php
natcasesort($files); // case insensitive "natural order" algorithm :: http://php.net/manual/en/function.natcasesort.php
return($files);
}
$images = returnimages(); //will get the array containing the images
foreach($images as $img)
{
echo '<img src="images/' . $img . '" />';
}
In my images folder, I have put 5 files for testing. And upon running it, it would give the following:
<img src="images/a.jpg" />
<img src="images/ba.jpg" />
<img src="images/ca.jpg" />
<img src="images/Copy (3) of a.jpg" />
<img src="images/Copy (4) of a.jpg" />

Categories