Welcome Guest, Not a member yet? Register   Sign In
sorting options with scandir()
#1

[eluser]brian88[/eluser]
So I have a function that scans all images in a folder. And in my view I loop through all the images and display them.

Scandir() by default sorts files alphabetically. Is there a way I can somehow sort them by date created?
Code:
public function index(){
   // scan all images
  $folder = FCPATH . "fonts/";
  $data['images'] = array_diff(scandir($folder), array('..', '.'));

  $this->load->view('header_view');
  $this->load->view('image_view', $data);
  $this->load->view('footer_view');
} // end function
#2

[eluser]CroNiX[/eluser]
Not that I know of. You'd probably have to do that manually. I'd also use filemtime() (last modified time) instead of the create date.

Code:
$i = array_diff(scandir($folder), array('..', '.'));

loop through those images, creating a new array like:
Code:
$images = array();
foreach($i as $img)
{
  //$images[modified_time] = image
  $images[filemtime(path/to/$img)] = $img;
}
Now just sort the $images array and they should be in order of the last file modification timestamp, Ascending. Reverse sort that to get descending.
#3

[eluser]brian88[/eluser]
Thanks cronix.

How do I sort by the time and not by the name?
Code:
public function index(){

   // scan all images
  $folder = FCPATH . "fonts/";
  $data['fonts'] = array_diff(scandir($folder), array('..', '.'));

  $images = array();
  foreach($data['fonts'] as $img){
   $images[filemtime($folder . $img)] = $img;
  }
  arsort($images);

  var_dump($images);
  /* returns
  array
  1338320766 => string 'zurich-bold-italic.png' (length=22)
  1338321685 => string 'zapf-humanist.png' (length=17)
  1338320711 => string 'white-bold.png' (length=14)
  1338321247 => string 'verdana.png' (length=11)
  1338321563 => string 'van-dijk.png' (length=12)

  its sorting by the name here. not the time. how do i fix this?
  */

  $this->load->view('header_view');
  $this->load->view('font_view', $data);
  $this->load->view('footer_view');
} // end function
#4

[eluser]brian88[/eluser]
Ohhh nvm I had to sort by the key, not the value


Code:
krsort($images);

Im trying to wrap my head around this logic. I get confused on how it works.
Code:
$data['images'] = array();
  foreach($data['fonts'] as $img){
   //your way. the right way
//$data['images'][filemtime($folder . $img)] = $img;

// way i would have done it. but i woulda got stuck prolly. wrong
   $data['images'][] = filemtime($folder . $img);
/* returns
array
50 => int 1338320766
49 => int 1338321685
48 => int 1338320711
*/
  }

Thanks cronix! You help me out a lot!




Theme © iAndrew 2016 - Forum software by © MyBB