Re: Recursive Iteration over a collection of objects

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Sun, Sep 7, 2008 at 11:05 AM, Jochem Maas <jochem@xxxxxxxxxxxxx> 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

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux