Re: Recursive Iteration over a collection of objects

From: Date: Mon, 08 Sep 2008 09:13:00 +0000
Subject: Re: Recursive Iteration over a collection of objects
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-279631@lists.php.net to get a copy of this message
Thanks very much to both of you. This does the trick! I had (stupidly) tried: foreach ($c as new RecursiveIteratorIterator($item)) which with hindsight is completely illogical! I also wasn't aware of the constants. Is there a simple tutorial / docs you know of for SPL? I have tried numerous google searches but the tutorials I have found assume I already know what I am talking about (big mistake:-) ). Even the PHP docs are very sparse. A real shame, as the SPL seems fantastic and I would love to use it more widely. One other thing... is there a mirror for this list? I'm sure SPL must have been covered many times before, but every time I try to search, the server times out. Thanks once again, David Nathan Nobbe wrote:
On Sun, Sep 7, 2008 at 11:05 AM, Jochem Maas <jochem@iamjochem.com <mailto:jochem@iamjochem.com>> wrote:
    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);
make sure to pass the appropriate mode when instantiating RecursiveIteratorIterator; the default is LEAVES_ONLY, which i presume is not what people want in most cases. here is the list of modes from the spl docs, /mode/ Operation mode (one of):
    * LEAVES_ONLY only show leaves
    * SELF_FIRST show parents prior to their childs
    * CHILD_FIRST show all children prior to their parent
so, i typically use SELF_FIRST, and then Jochem's example would become, .. foreach(new RecursiveIteratorIterator($c, RecursiveIteratorIterator::SELF_FIRST) as $item) .. -nathan


« previous php.general (#279631) next »