photo_id of each image for link inside foreach loop - php

What I'm trying to do is get the photo_id='.$pid.' of each photo for the link wrapped around them inside the foreach loop.
I tried $image['photo_id'] but that didn't work it just printed image symbols. I then wrapped a separate foreach loop around the current one and that duplicated the amount of images. I'm new to using the foreach loop with arrays and keys so still trying to get my head around it.
$images = array();
while ($rowhhh = mysqli_fetch_assoc($resulthhh)) {
$images[] = $rowhhh['photo_imagedata'];
$photo_id[] = $rowhhh['photo_id'];
}
foreach ($images as $image) {
if($photo_num==1){
echo '<img class="stream_images" style="width:200px;height:200px;object-fit:cover;margin:2px;padding:2px;" src="data:image/jpeg;base64,'. base64_encode($image) .'" />';
}else{
echo '<img class="stream_images" style="width:100px;height:100px;object-fit:cover;margin:2px;padding:2px;" src="data:image/jpeg;base64,'. base64_encode($image) .'" />';
}
}

Personally, I'd use the $images var as a multidimensional array to store the ID and the Data of each image. Then, you can access both of these bits of information easily in your foreach() loop.
$images = array();
while ($rowhhh = mysqli_fetch_assoc($resulthhh)) {
$imageArray = array(
'data' => $rowhhh['photo_imagedata'],
'id' => $rowhhh['photo_id']
);
$images[] = $imageArray;
}
foreach ($images as $image) {
if($photo_num==1){
echo '<img class="stream_images" style="width:200px;height:200px;object-fit:cover;margin:2px;padding:2px;" src="data:image/jpeg;base64,'. base64_encode($image['data']) .'" />';
}else{
echo '<img class="stream_images" style="width:100px;height:100px;object-fit:cover;margin:2px;padding:2px;" src="data:image/jpeg;base64,'. base64_encode($image['data']) .'" />';
}
}

Related

How to replace a single string with an array?

I have a string ..... one .... and I have an array that contains images link
$my_string = '..... one ....';
$images = [
"0" => "image_url_1",
"1" => "image_url_2",
]
I need to replace the word one with these two images
my code:
$pdf_form = ".... <span>one</span> ....";
foreach ($images as $image) {
$pdf_form = Str::replace('one', '<img src="' . $image . '" />', $pdf_form);
}
dd($pdf_form);
The output is, I got just the first image only!
How can I print both images?
Do it like this
$replace_string="";
foreach ($images as $image) {
$replace_string.='<img src="' . $image . '" />';
}
$pdf_form = Str::replace('one', $replace_string, $my_string);
I see only twos bugs. 1) You use declare $image but never used. Change this: foreach ($images as $image) {to foreach ($images as $value) {
In a loop you will always override the value if you asign the value o variable by using =. Change this to .=
Update
$pdf_form .= \Stthis line is in your code wrong. You assign with = but you have to concat the strings with .=
$pdf_form = ".... <span>one</span> ....";
$images = ['pic1.png', 'pic2.png'];
foreach ($images as $image) {
$pdf_form .= \Str::replace('one', '<img src="' . $image . '" />', $pdf_form);
}
dd($pdf_form);
output
^ ".... <span>one</span> ........ <span><img src="pic1.png" /></span> ........ <span><img src="pic2.png" /></span> ........ <span><img src="pic1.png" /></span> .... ◀"
Take a look at the strtr function.
If I understand your question correctly, you want to display both images each with their own <img> tag.
$my_string = '<img src="one" />';
$images = [
"0" => "image_url_1",
"1" => "image_url_2",
]
$pdf_form = '';
foreach ($images as $image) {
$pdf_form = $pdf_form . strtr($my_string, ['one' => $image]);
}

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));
}

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>';
}

foreach inside foreach issue

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>';
}
}

echo image url with tags in php

I have previously asked a question on how to echo the url of images from an html page. I can do this successfully but how can I narrow this down further so only images urls beginning with a certain phrase are shown, furthermore how can I add an image tag around them so the images are displayed as images and not just text?
e.g I only want to list images beginning with http://photos.website.com.
edit: I forgot to mention this is the code used to iterate through the images:
foreach($images as $image) {
echo $image->getAttribute('src') . '<br />';
}
You will have to add a condition that tests the content of $image->getAttribute('src').
To test if a string beings by another, a possibility is to use the strpos function, which returns the position of the needle in the haystack -- here, you want that position to be 0 (i.e. the first character of the string).
foreach($images as $image) {
$url = $image->getAttribute('src');
if (strpos($url, 'http://photos.website.com') === 0) {
echo $url . '<br />';
}
}
Simple:
foreach ($images as $image) {
$src = $image->getAttribute('src');
if (stripos($src, 'http://photos.website.com') === 0)
{
echo $src . '<br />';
}
}
And to add tags:
foreach ($images as $image) {
$src = $image->getAttribute('src');
if (stripos($src, 'http://photos.website.com') === 0)
{
echo sprintf('<img src="%s" alt="" />', $src) . "\n";
}
}

Categories