2012-03-26 30 views
2

一個multidmentional陣列的葉節點值I有一個這樣的陣列:如何得到具有1-N的水平PHP

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

我想獲得的值:

540 , 671 ,680 , 400 

的問題是,這個陣列正在增長,並且不知道有多少深度,

+0

http://stackoverflow.com/questions/3899971/implode-and-explode-multi-dimensional-arrays 有關。並且應該給你你的答案。 – Platipuss 2012-03-26 12:36:46

+0

[How to Flatten a Multidimensional Array?](http://stackoverflow.com/questions/1319903/how-to-flatten-a-multidimensional-array) – hakre 2012-06-23 12:29:01

回答

3

您可以使用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 
+0

非常感謝。它完美的工作................ – 2012-03-26 13:56:19

2

這裏的解決方案:

$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