简体   繁体   中英

PHP RecursiveIteratorIterator - Reverse and Count results

I have the following:

<?php

$path = '/home/user/test';

$dir = new RecursiveDirectoryIterator( $path  );
$iterator = new RecursiveIteratorIterator( $dir );
$dir_iterator = new RegexIterator( $iterator, '/^.+\.php/i', RecursiveRegexIterator::GET_MATCH );

?>

So far so good, but I need to reverse the results , to archive the same effect as array_reverse()

I tried like this, with no success:

<?php

$dir_iterator = array_reverse( (array)$dir_iterator );

?>

Also, how can I get the number of results returned ? I tried this, but isn't working:

<?php

$total_results = count( $dir_iterator );

?>

Can anybody help me out?

Many thanks in advance!

What you need is iterator_to_array you can try

$dir_iterator =  array_reverse(iterator_to_array($dir_iterator ));

To count Iterators what you need is :

$total_results = iterator_count( $dir_iterator );

Better Sill Implement Yours

$dir_iterator = new ReverseIterator($dir_iterator);

foreach ( $dir_iterator as $file ) {
    // do your thing
}

// To get total
echo count($dir_iterator);

Class Used

class ReverseIterator extends ArrayIterator implements Countable {
    private $t;

    public function __construct(Iterator $it) {
        $r = array_reverse(iterator_to_array($it));
        $this->t = count($r);
        parent::__construct($r);
        unset($r);
    }

    function count() {
        return $this->t;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM