note 106519 added to class.recursivearrayiterator
| From: | c dot 1 at smithies dot org | Date: | Tue, 15 Nov 2011 18:29:17 +0000 |
| Subject: | note 106519 added to class.recursivearrayiterator | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-184515@lists.php.net to get a copy of this message | ||
If you are iterating over a multi-dimensional array of objects, you may be tempted to use a
RecursiveArrayIterator within a RecursiveIteratorIterator. You are likely to get baffling results if
you do. That is because RecursiveArrayIterator treats all objects as having children, and tries to
recurse into them. But if you are interested in having your RecursiveIteratorIterator return the
objects in your multi-dimensional array, then you don't want the default setting LEAVES_ONLY,
because no object can be a leaf (= has no children).
The solution is to extend the RecursiveArrayIterator class and override the hasChildren method
appropriately. Something like the following might be suitable:
<?php
class RecursiveArrayOnlyIterator extends RecursiveArrayIterator {
public function hasChildren() {
return is_array($this->current());
}
}
?>
Of course, this simple example will not recurse into ArrayObjects either!
----
Server IP: 69.147.83.197
Probable Submitter: 109.151.9.102
----
Manual Page -- http://www.php.net/manual/en/class.recursivearrayiterator.php
Edit -- https://master.php.net/note/edit/106519
Del: integrated -- https://master.php.net/note/delete/106519/integrated
Del: useless -- https://master.php.net/note/delete/106519/useless
Del: bad code -- https://master.php.net/note/delete/106519/bad+code
Del: spam -- https://master.php.net/note/delete/106519/spam
Del: non-english -- https://master.php.net/note/delete/106519/non-english
Del: in docs -- https://master.php.net/note/delete/106519/in+docs
Del: other reasons-- https://master.php.net/note/delete/106519
Reject -- https://master.php.net/note/reject/106519
Search -- https://master.php.net/manage/user-notes.php