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++;
      }
    }
  ?>
3
  • 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"? Commented Mar 6, 2016 at 19:24
  • if you mean "sort by filename", natsort() would probably serve you well - php.net/manual/en/function.natsort.php Commented Mar 6, 2016 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. Commented Mar 6, 2016 at 19:29

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.