获取不确定深度的多维数组的叶节点值 [英] Get the leaf node values of a multi-dimensional array with an indeterminant depth

查看:82
本文介绍了获取不确定深度的多维数组的叶节点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数组:

I have an array like this:

Array
(
    [23] => 540,
    [25] => Array
        (
            [656] => Array(671 ,680),
            [345] => 400
        )
)

我想获取值:

540, 671, 680, 400

对我来说,问题是,这个数组正在增长,我不知道它将有多少层.

The problem for me is, that this array is growing and I don't know how many levels deep it will be.

推荐答案

您可以使用SPL的 RecursiveIteratorIterator 及其LEAVES_ONLY标志.

You can use SPL's RecursiveArrayIterator and RecursiveIteratorIterator with its LEAVES_ONLY flag.

独立的示例:

<?php
$rai = new RecursiveArrayIterator(getData());
// $rii = new RecursiveIteratorIterator($rai, RecursiveIteratorIterator::LEAVES_ONLY) - but this is the default
$rii = new RecursiveIteratorIterator($rai);
foreach($rii as $n) {
    echo $n, "\n";
}

// test data source    
function getData() {
    return array(
        23 => 540,
            25 => array(
                656 => array(671,680),
                345 => 400
            )
    );
}

打印

540
671
680
400

这篇关于获取不确定深度的多维数组的叶节点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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