获取深度不确定的多维数组的叶节点值


Get the leaf node values of a multi-dimensional array with an indeterminant depth

我有一个这样的数组:

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

我想得到值:

540, 671, 680, 400

我的问题是,这个数组正在增长,我不知道它会有多深。

您可以使用SPL的RecursiveArrayIteratorRecursiveIteratorIterator及其LEAVES_ONLY标志。

独立示例:

<?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

以下是解决方案:

$array = array
(
    23 => 540,
    25 => array
        (
            656 => array(671,680),
            345 => 400
        )
);
var_dump($array);
$result = array();
function fn($item, $key){
    global $result;
    if (!is_array($item)){
        $result[] = $item;
    }
}
array_walk_recursive($array, 'fn');
var_dump($result);

以及结果

array
  23 => int 540
  25 => 
    array
      656 => 
        array
          0 => int 671
          1 => int 680
      345 => int 400
array
  0 => int 540
  1 => int 671
  2 => int 680
  3 => int 400