How can I combine two arrays for a loop? - php

I'm stuck on this for a while now: I'm trying to combine two arrays, one is every image in a folder, and the other one is the description of the picture from the SQL Database. In the database I've added the filename and the apartment name. To make my query work I need it to be in a loop, but to show the results of my query, it needs to become a loop, so I would think it must be possible to combine it right? But I can't seem to figure out how to combine these two arrays in a loop. I've tried with two loops and this is what I've got:
<?php
$directory = "images/photos/";
$images = glob('images/photos/*.{jpg,png,gif}', GLOB_BRACE);
foreach ($images as $image) {
$sqlaa = "SELECT * FROM `afbeelding` WHERE filename = ' . $image . '";
$titles = mysqli_query($link, $sqlaa);
while ($row = $titles->fetch_array()) {
echo '<form action="" method="post"><li>
<a href="' . $image . '" title="' . $row['apartment'] . '" >
<img style="width:150px;height:150px;" src="' . $image . '" />
</a>
</li>';
}
}
?>
If anyone knew, that'd be great!
Thanks in advance

You can try making the loop over the data and then check the image in the loop, this could be faster and avoids using a query inside a loop.
<?php
$directory = "images/photos/";
//$images = glob('images/photos/*.{jpg,png,gif}', GLOB_BRACE);
$sqlaa = "SELECT filename,apartment FROM `afbeelding`";
$titles = mysqli_query($link, $sqlaa);
while($row = $titles->fetch_array())
{
$image=$row["filename"];
if (file_exists($directory.$image)){
echo '<form action="" method="post"><li>
<a href="'.$image.'" title="' . $row['apartment'] . '" >
<img style="width:150px;height:150px;" src="'.$image.'" />
</a>
</li>';
}
}
?>
I don't know if the image is stored using the full relative path "images/photos/img.png" or the base filename only "img.png".
If the data in afbeelding is huge, you can improve the sql query using an IN filter
function imageNames($item){
return "'$item'";
}
$images = glob('images/photos/*.{jpg,png,gif}', GLOB_BRACE);
$names=array_map("imageNames",$images);
$filter_names=implode(",",$names);
$sqlaa = "SELECT filename,apartment FROM `afbeelding` WHERE filename IN ($filter_names)";
And then proceed with the loop, without checking files.

How about... going about it differently.
You already have the filenames in database.
So just poll your database with your available data, and then just echo it.
I'm assuiming it's stored as images/photos/filename.jpg in your database.
But without a data sample as is in your database I can't speculate more.
$directory = "images/photos/";
foreach ($images as $image) {
$sqlaa = "SELECT * FROM `afbeelding` WHERE filename like '%images/photos/%'";
$titles = mysqli_query($link, $sqlaa);
while ($row = $titles->fetch_array()) {
echo '<form action="" method="post"><li>
<a href="' . $image . '" title="' . $row['apartment'] . '" >
<img style="width:150px;height:150px;" src="' . $row['filename'] . '" />
</a>
</li>';
}
}

first: loops on db-calls are not really best practice..
A possible result to your question:
<?php
$directory = "images/photos/";
$images = glob('images/photos/*.{jpg,png,gif}', GLOB_BRACE);
$images = array_flip($images);
// get data first
foreach($images as $image => $v) {
$sqlaa = "SELECT * FROM `afbeelding` WHERE filename = ' . $image . '";
$titles = mysqli_query($link, $sqlaa);
if ($title->num_rows == 1) {
$row = $titles->fetch_array();
$images[$image] = $row['apartment'];
} else {
$images[$image] = '';
}
}
// render data
foreach ($images as $filename => $description) {
echo '<form action="" method="post"><li>
<a href="'.$filename.'" title="' . $description . '" >
<img style="width:150px;height:150px;" src="'.$filename.'" />
</a>
</li>';
}
?>
Not really nice, but plain simple..

Related

PHP - If... statement to insert collapsible div where a particular string is found

I have a list of image URLs stored in a database, separated by line breaks. The following PHP code displays them on my site:
$images = explode("\n", $value );
$value = '';
foreach ($images as $im){
$value .= '<img src="'. $im . '" style="max-width:1024px"/> <br />';
}
However, I want to hide some of the images behind a collapsible div if they contain a particular string.
Is it possible to write an if statement so $value changes to some HTML code displaying a collapsible div?
For example:
Rather than $value:
<img src="'. www.example.com/hiddenimage1.jpg . '" style="max-width:1024px"/> <br />
It would become:
<div class="collapsiblediv" style="etc etc"><img src="'. www.example.com/hiddenimage1.jpg . '" style="max-width:1024px"/> <br /></div>
However anything NOT containing "hiddenimage" would display as usual.
Is it possible?
You can use the strstr() function of PHP to search for a chunk of a string within a string.
Using this function, you can search for the value 'hiddenimage' within your foreach loop. Based on a conditional, you could then return either the collapsible <div> or the <img>
You could try this code
$images = explode("\n", $value );
$value = '';
foreach ($images as $im){
if(strstr( $im, 'hiddenimage' ) {
<div class="collapsiblediv" style="etc etc"><img src="'.
$im . '" style="max-width:1024px"/> <br
/></div>
} else {
$value .= '<img src="'. $im . '" style="max-width:1024px"/> <br />';
}
}

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.

limit results in foreach loop

The code below I have works fine but I wanted to check with you, the experts, to make sure I was using best practices.
I want to limit the loop results to 16. Does the code below seem like the best method?
Thanks,
Jeffrey
foreach ($flickr_set['items'] as $id => $photos) {
$ctr=0;
foreach ($photos as $photo) {
if($ctr>=16) break; else $ctr++; /* limits results to 16 */
echo '<a href="' . $photo['large'] . '" title="' . $photo['title'] . '" rel="flickr-set" ><img src="' . $photo['thumb'] . '" /></a>';
}
}
Your solution is fine, if you want a more structured solution which might be also more understandable, you can use array_slice:
foreach ($flickr_set['items'] as $id => $photos) {
foreach (array_slice($photos, 0, 16) as $photo) {
echo '<a href="' . $photo['large'] . '" title="' . $photo['title'] . '" rel="flickr-set" ><img src="' . $photo['thumb'] . '" /></a>';
}
}
Your code is fine but..
I woudn't check if it is higher or equal i would only check if it equal like this:
if($ctr == 16)

ACF Repeater showing ID, not URL

I'm using the Advanced Custom Fields Repeater to pump out the image URL. But, it shows the ID, not the URL. Any help is greatly appreciated, thanks. Here is my code:
<?php
$rows = get_field('images');
foreach($rows as $row){
$image = wp_get_attachment_image_src(get_sub_field('image'), 'full');
//var_dump($row['image']);
echo '<img src="'. $row['image']['url'] . '" class="shadowed forced">';
}
?>
In response to your question, it doesn't work because get_sub_field has to be used in a while statement in conjunction with has_sub_field(), and because your $row['image']['url'] is referring to an the image object (set via return value on the field menu), while is seems as if you are actually having the field return the 'Attachment ID'.
If you want to use a foreach with the return value set to 'Attachment ID', you need to use the object/array that is being returned like so:
<?php
$rows = get_field('images');
foreach($rows as $row){
$image = wp_get_attachment_image_src($row['image'], 'full');
echo '<img src="'. $image[0] . '" class="shadowed forced">';
}
?>
If you want to use the foreach method, with the return value set to 'Image Object', it should look something like this:
<?php
$rows = get_field('images');
foreach($rows as $row){
echo '<img src="'. $row['image']['url'] . '" class="shadowed forced">';
}?>
Another solution, working of your answer/suggestion would be to set the fields return value to 'Image URL', and then you could simply call the image like so:
<?php $rows = get_field('images');
if ($rows)
{
while (has_sub_field('images'))
{
$image = get_sub_field('image');
echo '<img src="'. $image . '" class="shadowed forced">';
}
} ?>
Alternatively if you wanted to show a different size of the image, you could also set the 'Return Value' to 'Image Object', and do something like this:
<?php $rows = get_field('images');
if ($rows)
{
while (has_sub_field('images'))
{
$image = get_sub_field('image');
echo '<img src="'. $image['sizes']['large'] . '" class="shadowed forced">';
}
} ?>
Looks like what I needed to do was not use a foreach, and instead just use and if & while statement. I was calling in the repeater, not the subfield with the old code. Here's a reference if anyone runs into this issue -
<?php
$rows = get_field('images');
if ($rows)
{
while (has_sub_field('images'))
{
$image = wp_get_attachment_image_src(get_sub_field('image'), 'full');
echo '<img src="'. $image[0] . '" class="shadowed forced">';
}
}
?>

Syntax problem with html in PHP

im getting a syntax error on this line of code and don't know the correct formatting for it.
This is the part i'm having problems with -
echo "
<ul>";
foreach($photos as $photo) {
$farm = $photo['farm'];
$server = $photo['server'];
$photo_id = $photo['id'];
$secret = $photo['secret'];
$photo_title = $photo['title'];
<li><img src="http://farm'.$photo['farm'].'.static.flickr.com/'.$photo['server'].'/'.$photo['id'].'_'.$photo['secret'].'_t.jpg" alt="'.$photo['title'].'" ></li>
The problem is with that li tag. How can i format it properly?
Per the comments, you probably mean to have the following for your last line:
echo '<li><img src="http://farm'.$photo['farm'].'.static.flickr.com/'.$photo['server'].'/'.$photo['id'].'_'.$photo['secret'].'_t.jpg" alt="'.$photo['title'].'" ></li>';
The <li> part should be quoted. Try:
echo "
<ul>";
foreach($photos as $photo) {
$farm = $photo['farm'];
$server = $photo['server'];
$photo_id = $photo['id'];
$secret = $photo['secret'];
$photo_title = $photo['title'];
echo '<li><img src="http://farm' . $photo['farm'] . 'static.flickr.com/' . $photo['server'] . '/' . $photo['id'] . '_' . $photo['secret'] . '_t.jpg" alt="' . $photo['title'] . '" ></li>';
}
echo '</ul>';

Categories