Hey guys, I'm getting some unexpected results when trying to use ArrayIterator - but since it's undocumented this might be correct. When I use a DirectoryIterator to traverse a directory I can't seem to create an array containing all of the directory elements. I've tried using references as well as clones of each object result. All I can seem to get is an array with the right *number* of file objects, but the objects are empty.

Ultimately, I'd like to be able to get an array of all of the files in a directory and reorder them, say, by file creation time (fileCTime).

Example code:

<?php

// Basically a DirectoryIterator with a few utility functions
class File_Linux extends DirectoryIterator {
  // Format to use for fileCTime timestamps
  const CTIME = '%c';

  function __toString()
  {
    $file = $this->current();
    return '<file>' .
           '<name>'  . $file->getFileName() . '</name>'  .
           '<type>'  . $file->getType()     . '</type>'  .
           '<ctime>' . strftime(self::CTIME, $file->getCTime()) . '</ctime>' .
           '<size>'  . $file->getSize()     . '</size>'  .
           "</file>\n";
  }

  function sortCTime(DirectoryIterator $file1, DirectoryIterator $file2)
  {
    $time1 = $file1->getCTime();
    $time2 = $file2->getCTime();
    if ($time1 == $time2) {
      return 0;
    }
    return $time1 > $time2 ? 1 : -1;
  }
}

$fm = new File_Linux('./');
echo '<pre>';

// Doesn't work - right number, put properties get lost
foreach ($fm as &$file) {
  $list[] = clone $file;
}
usort($list, array('File_Linux', 'sortCTime'));
print_r($list);

// Doesn't work either
foreach ($fm as &$file) {
  $list2[] =& $file;
}
usort($list2, array('File_Linux', 'sortCTime'));
print_r($list2);

?>

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Reply via email to