Accessing array object variables when implementing RecursiveArrayIterator in RecursiveIteratorIterator

StackOverflow https://stackoverflow.com/questions/4014035

  •  26-09-2019
  •  | 
  •  

문제

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'
            ),
          )),
도움이 되었습니까?

해결책

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.

다른 팁

Assuming $hierarchy is your large array, you can use $hierarchy["foo"] to access the value associated with the foo key. Or like this:

$my_key = "foo"
echo $hierarchy[$my_key]
// Same as
echo $hierarchy["foo"]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top