PHP递归迭代器:当前数组迭代的父键? [英] PHP Recursive Iterator: Parent key of current array iteration?

查看:92
本文介绍了PHP递归迭代器:当前数组迭代的父键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数组:

I have an array like this:

$arr = array(
        $foo = array(
            'donuts' => array(
                    'name' => 'lionel ritchie',
                    'animal' => 'manatee',
                )
        )
    );

使用"SPL递归迭代器"的魔力和此代码:

Using that magic of the 'SPL Recursive Iterator' and this code:

$bar = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));

    foreach($bar as $key => $value) 
    {
        echo $key . ": " . $value . "<br>";
    }

我可以遍历多维数组并返回键=>值对,例如:

I can traverse the multidimensional array and return the key => value pairs, such as:

名称:lionel ritchie 动物:海牛

name: lionel ritchie animal: manatee

但是,我还需要返回当前迭代数组的PARENT元素,所以...

However, I need to return the PARENT element of the current iterated array as well, so...

甜甜圈名称:lionel richie 甜甜圈动物:海牛

donuts name: lionel richie donuts animal: manatee

这可能吗?

(我只知道所有递归迭代器"的内容,因此,如果我遗漏了一些明显的内容,我表示歉意.)

(I've only become aware of all the 'Recursive Iterator' stuff, so if I'm missing something obvious, I apologise.)

推荐答案

您可以通过getSubIterator访问迭代器,在这种情况下,您需要密钥:

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>';

}

?>

这篇关于PHP递归迭代器:当前数组迭代的父键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆