如何使用RecursiveIteratorIterator获取特定值

时间:2016-12-27 17:49:17

标签: php arrays iterator

我想使用RecursiveIteratorIterator获取多维数组的特定值

如果可能,我想让它像普通循环一样

$ VAL ['键'];

我的代码

$data = array(
    'title' =>'how to work',
    'posts' => array(
        array(
            'title' => 'introduction to iterators',
            'email' => 'kingahmadz@hotmail.com'
        ),
        array(
            'title' => 'introduction to iterators2',
            'email' => 'kingahmadz@hotmail.com'
        ),
        array(
            'title' => 'introduction to iterators3',
            'email' => 'kingahmadz@hotmail.com'
        ),
    ));


foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($data)) as $item => $val) {
  echo $val['email'];
}

4 个答案:

答案 0 :(得分:1)

实际上,对于这种简单的情况,使用RecursiveIteratorIterator对象会过于复杂并且不是最佳的。
如果它只是用于测试,请使用以下方法:

$key = 'email';
$it = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($data), \RecursiveIteratorIterator::CATCH_GET_CHILD);
$emails = array_column($it->getInnerIterator()['posts'], $key);

print_r($emails);

输出:

Array
(
    [0] => kingahmadz@hotmail.com
    [1] => kingahmadz@hotmail.com
    [2] => kingahmadz@hotmail.com
)

如果不使用迭代器并同时应用array_column函数来获得相同的结果,那就更简单了:

$emails = array_column($data['posts'], $key);

答案 1 :(得分:1)

如果您只需要收到所有电子邮件,则应使用array_column

$posts = $data['posts'];

foreach (array_column($posts, 'email') as $email) {
    echo $email, PHP_EOL;
}

然而,如果您需要获取所有电子邮件的值,无论深度如何,您都有多个选项

使用简单的RecursiveIteratorIterator

$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($data)
);

foreach ($iterator as $key => $value) {
    if ($key === 'email') {
        echo $value, PHP_EOL;
    }
}

使用RecursiveCallbackFilterIteratorRecursiveFilterIterator

$iterator = new RecursiveIteratorIterator(
    new RecursiveCallbackFilterIterator(
        new RecursiveArrayIterator($data), 
        function ($_, $key, $iterator) {
            if($iterator->hasChildren()) {
                return true;
            }

            return $key === 'email'; 
        }
    )
);

foreach ($iterator as $email) {
    echo $email, PHP_EOL;
}

使用RecursiveRegexIterator

$iterator = new RecursiveIteratorIterator(
    new RecursiveRegexIterator(
        new RecursiveArrayIterator($data),
        '/^email$/',
        RegexIterator::MATCH,
        RegexIterator::USE_KEY
    )
);

foreach ($iterator as $email) {
    echo $email, PHP_EOL;   
}

这是working demo

答案 2 :(得分:0)

在您的示例中,$item是关键,$val是值。如果要输出特定键,则可以执行以下操作:

foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($data)) as $item => $val) {
    if ($item == 'email') {
        echo $val . '<br />';
    }
}

答案 3 :(得分:0)

您可以解释为什么需要使用RecursiveIteratorIterator因为在您的例子中您可以使用array_column来获取电子邮件

array_column($data['posts'], 'email')