1

I want to get picture from few sub-folder in a directory and i want to sort them as data. with the Following code I got the images now i want to sort them as data.

Note

every image name starts with the date and time of uploading example :-

default image name = "image.jpg"

after upload image name = "24-02-2016-09-42-33-image.jpg"

<?php
    $dir = 'dist/userdata/'.$username.'/photos/';

    if ($opendir = opendir ($dir) ) {

      $files = 0;

      while (($file = readdir ($opendir)) !== false && $files <= 2 + 1 ) {

        if ($file !="." && $file !="..") {

          $newdir = $dir.''.$file.'/';

          if ($newopendir = opendir ($newdir)) {
            $imgs = 0;
            while (($img = readdir ($newopendir)) !== false && $imgs <= 3 + 1) {
              if ($img !=="." && $img !=="..") {

                $supported_files = array(
                  'jpeg',
                    'jpg',
                    'png'
                );
                $ext = strtolower(pathinfo($img, PATHINFO_EXTENSION)); 
                if (in_array($ext, $supported_files)) {
                  echo '<img src="'.$newdir.''.$img.'"/>';
                } else {
                }
              }
              $imgs++;
            }
          }

        }
        $files++;
      }
    }
  ?>
Fin
  • 386
  • 1
  • 15
saqib kifayat
  • 136
  • 2
  • 14
  • is there an actual question here? or do you just want someone to write the code for you? also, what do you mean by "sort as data"? – hanshenrik Mar 06 '16 at 19:24
  • if you mean "sort by filename", natsort() would probably serve you well - http://php.net/manual/en/function.natsort.php – hanshenrik Mar 06 '16 at 19:26
  • with the above code i am getting images from sub-folders of a directory the code is working (i am getting images) but sorted by filename. I want them to sort by date mean last uploaded image on the top. – saqib kifayat Mar 06 '16 at 19:29

1 Answers1

1

Instead of echoing images imidiatelly, gather them into array. After that you can easily sort them with usort()

Also - you are not closing handles after opening them.

And, probably RecursiveDirectoryIterator would be better fit for this than nested whiles.

potfur
  • 171
  • 1
  • 5