Recursive Iteration over a collection of objects
| From: | David Lidstone | Date: | Thu, 04 Sep 2008 11:24:47 +0000 |
| Subject: | Recursive Iteration over a collection of objects | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-279498@lists.php.net to get a copy of this message | ||
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?), 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;}
}