Quantcast
Channel: Evaggelos Balaskas - System Engineer
Viewing all articles
Browse latest Browse all 333

PHP Sorting Iterators

$
0
0

Iterator

a few months ago I wrote an article on RecursiveFilterIterator, you can find the article here: PHP Recursive Directory File Listing . If you run the example code, you will see that output is not sorted.

Object

RecursiveIteratorIterator is actually an object, so it is a little difficult to sort using the known php functions. To give you and example:

$Iterator = new RecursiveDirectoryIterator('./');
foreach ($Iterator as $file)
    var_dump($file);
object(SplFileInfo)#7 (2) {
  ["pathName":"SplFileInfo":private]=>
  string(12) "./index.html"
  ["fileName":"SplFileInfo":private]=>
  string(10) "index.html"
}

Internet Answers

Unfortunately stackoverflow and other related online results provide the most complicated answers on this matter. I understand that this is not an easy subject to discuss but I dont get the extra complexity of some responses.

Back to basics

So let us go back a few steps to understand what an iterator is. An iterator is an object that we can iterate! That means we can use a loop to walk through the data of an iterator. Reading the above output you can get hopefully an better idea.

But we can also use an Iterator as an array!

eg.

$It = new RecursiveDirectoryIterator('./');
foreach ($It as $key=>$val)
    echo $key.":".$val."n";

output:

./index.html:./index.html

Arrays

So it is difficult to sort Iterators, but it is easy to sort arrays!
We just need to convert the Iterator to an Array:

$array = iterator_to_array($Iterator);

that’s it!

Sorting

For my code I need to reverse sort the array by key (filename on a recursive directory), so my sorting looks like:

krsort( $array );

easy, right?

New Iterator

After sorting, we need to change back an iterator object format:

$Iterator = new ArrayIterator($array);

and that’s it !

Code

the entire code in one paragraph:

<?php
// ebal, Fri, 07 Jul 2017 22:01:48 +0300

// Directory to Recursive search
$dir = "/tmp/";

// Iterator Object
$files =  new RecursiveIteratorIterator(
          new RecursiveDirectoryIterator($dir)
          );

// Convert to Array
$Array = iterator_to_array ( $files );
// Reverse Sort by key the array
krsort ( $Array );
// Convert to Iterator
$files = new ArrayIterator( $Array );

// Print the file name
foreach($files as $name => $object)
    echo "$namen";

?>
Tag(s): php, iterator

Viewing all articles
Browse latest Browse all 333

Trending Articles