phpsplarrayiterator

Accessing array object variables when implementing RecursiveArrayIterator in RecursiveIteratorIterator


I have a large arrayObject which I'm looping over using the following:-

$rit = new RecursiveIteratorIterator(new RecursiveArrayIterator($hierarchy));
foreach($rit as $key=> $val) {

}

How can I access the a specific key within the array? I can access them by echoing $key and the $val but I have specific keys I wish to access. If I attempt to call $key[''] I get the first letter on the key name.

Edit 1

Some sample data (There can be many different sub-children too):

ArrayObject::__set_state(array(
   0 => 
  ArrayObject::__set_state(array(
     0 => 
    array (
      'id' => '8755',
      'company_id' => '1437',
      'name' => 'Name 1'
    ),
     1 => 
    ArrayObject::__set_state(array(
       0 => 
      ArrayObject::__set_state(array(
         0 => 
        array (
          'id' => '8763',
          'company_id' => '1437',
          'name' => 'Name 2'
        ),
         1 => 
        ArrayObject::__set_state(array(
           0 => 
          ArrayObject::__set_state(array(
             0 => 
            array (
              'id' => '9067',
              'company_id' => '1437',
              'name' => 'Name 3'
            ),
          )),
           1 => 
          ArrayObject::__set_state(array(
             0 => 
            array (
              'id' => '8765',
              'company_id' => '1437',
              'name' => 'Name 4'
            ),
          )),
           2 => 
          ArrayObject::__set_state(array(
             0 => 
            array (
              'id' => '9049',
              'company_id' => '1437',
              'name' => 'Name 5'
            ),
          )),
           3 => 
          ArrayObject::__set_state(array(
             0 => 
            array (
              'id' => '8769',
              'company_id' => '1437',
              'name' => 'Name 6'
            ),
          )),

Solution

  • By default, the RecursiveIteratorIterator will only list the leaves. Try

    $rit = new RecursiveIteratorIterator(
               new RecursiveArrayIterator($hierarchy),
               RecursiveIteratorIterator::SELF_FIRST);
    

    to get the containing elements as well.