Recover scandir images from PHP and print incrementing according to the number of occurrences

Asked

Viewed 125 times

0

I need to recover images from a folder and I only have the reference number recorded in the database. I also have to create an increment, because for each reference can have n images.

Combining the functions scandir and strstr of PHP I can recover, but despite printing correctly what I need, in case the 6 images as in example 1 "$Domain", it does not filter the other results, making it difficult to create the right increment, type photo-1- ... photo-2- ... etc.

Adding the line break if you notice the other hidden results, making the increment grab all results from the folder. I appreciate any solution.

The images are saved as follows: Ex: photo-1-0023.jpg, photo-2-0023.jpg

$dir    = '../assets/Imagens/';
$files = scandir($dir);


foreach ($files as $key => $value) :
    $conta=1;
    //$domain = strstr($value, "foto-".$conta++."-".$row['referencia']);
    // Exemplo 1

    $domain = strstr($value,  $row['referencia']);

    echo $domain ; 
    // imprime 00234.jpg00234.jpg00234.jpg00234.jpg00234.jpg00234.jpg (6 imagens)

    echo $domain.'<br>' ; 
    //imprime 00234.jpg


    //00234.jpg
    //00234.jpg



    //00234.jpg
    //00234.jpg
    //00234.jpg

endforeach;

2 answers

1

You can make it easy by saving the partial path in the bank and avoiding a folder loop that is more costly for code to execute, save "/Assets/Images/image001.jpg" in the bank and recover with a:

"http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']. $Row['img_url']"

$Row being the array that will come from the loop in the bank.

If it’s unfeasible, I can help you think of the same line you’re doing at the moment.

  • OK thanks @Daneil Costa, I’m doing tests and as soon as we can we continue.

-1


Thanks for the suggestion Daniel, but I ended up solving it in another way. It is not the most elegant but it worked both to print and to change the files.

<?php
    //select para obter a referencia

    $d=0;
    $m=0;                    

    //loop para buscar as imagens foto-1, foto-2, ...
    for ($i=0; $i<99; $i++) :
        $fotopasta ="assets/Imagens/foto-".++$m."-" .$row['referencia'] .".jpg";

        //se a imagem existir insere no array
        if(file_exists($fotopasta)) :
            $fotopastaArray[] = $fotopasta;
        endif;
    endfor;

    //percorro a string e descubro o numero da ultima imagem
    $qtd_fotos = substr(end($fotopastaArray), 20,2);

    //monto outro loop com o numero correto de ocorrencia
    for ($n=0; $n < $qtd_fotos; $n++) :
        $foto ="assets/Imagens/foto-".++$d."-".$row['referencia'].".jpg"; ?>
        <?php if (file_exists($foto)) :  ?>
            <li><img src="<?php echo $foto ; ?>" alt="<?php echo utf8_encode($row['nome']) ; ?>"></li>
        <?php else : endif;  
    endfor; 
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.