Re: Recursive Iteration over a collection of objects
| From: | Jochem Maas | Date: | Sun, 07 Sep 2008 17:05:37 +0000 |
| Subject: | Re: Recursive Iteration over a collection of objects | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-279613@lists.php.net to get a copy of this message | ||
David Lidstone schreef:
Hi I am getting myself quite confused while trying to use SPL to recursively iterate through a collection of objects, and any help would be greatly appreciated! My collection of objects is contained in a class (which I frequently use to iterate through objects stored in an array in the class), and I think my hasChildren() and getChildren() methods are working ok, but I am unable to make it recursive. I am particularly confused by where I have to use RecursiveIteratorIterator (do I have to at all?),something like: $c = new Categories; $c->loadAll(); foreach (new RecursiveIteratorIterator($c) as $item) var_dump($item);
and the getIterator() method (again, do I need it and why?). Am I going about this totally the wrong way to start with? I have tried to summarise my code below. Sorry for the long post, and thanks again. David ====== Script... ========== $categories = new RecursiveIteratorIterator(new Categories); $categories->loadAll(); foreach ($categories as $category) {echo 'ID: ' . $category->getID(); echo 'Level: ' . $category->getLevel();} ======= classes... ========= abstract class ObjCollection implements RecursiveIterator {// class stores objects in an array public $objs = array(); public function current(); public function hasChildren(); // etc etc} class Categories extends ObjCollection {// concrete class which loads the Category objects into // the ObjCollection array public function loadAll() {// ...load Category classes // into parent:: !}} class Category {private $id; private $level public function getID() {return $this->id;} public function getLevel() {return $this->level;}}