PHP Recursive Iterator: Parent key of current array iteration?

后端 未结 1 391
无人共我
无人共我 2021-01-04 06:32

I have an array like this:

$arr = array(
        $foo = array(
            \'donuts\' => array(
                    \'name\' => \'lionel ritchie\',
            


        
相关标签:
1条回答
  • 2021-01-04 07:03

    You can access the iterator via getSubIterator, and in your case you want the key:

    <?php
    
    $arr = array(
        $foo = array(
            'donuts' => array(
                    'name' => 'lionel ritchie',
                    'animal' => 'manatee',
                )
        )
    );
    $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
    
    foreach ($iterator as $key => $value) {
        // loop through the subIterators... 
        $keys = array();
        // in this case i skip the grand parent (numeric array)
        for ($i = $iterator->getDepth()-1; $i>0; $i--) {
            $keys[] = $iterator->getSubIterator($i)->key();
        }
        $keys[] = $key;
        echo implode(' ',$keys).': '.$value.'<br>';
    
    }
    
    ?>
    
    0 讨论(0)
提交回复
热议问题