2010-12-13 100 views
2

我怎樣才能獲得值這個數組的:如何獲得維數組中的值?

Array 
(

    [0] => 20 
    [1] => Array 
     (
      [0] => 21 
      [1] => 22 
      [2] => Array 
       (
        [0] => 23 
        [1] => Array 
         (
          [0] => 52 
          [1] => 
         ) 

       ) 

     ) 

) 

我要得到這個值:20,21,22,23和52提前

謝謝! :)

+5

*哪個*值?! – deceze 2010-12-13 03:05:58

+0

你以後哪個價值? – Phil 2010-12-13 03:06:03

+1

哪個值?哪個陣列?有4! – 2010-12-13 03:06:25

回答

0

我要得到這個值:20,21,22,23和52

譯爲得到所有值的數組一個原始數組的遞歸。使用標準array_walk_recursive功能...

 

$test_array = array(
    20, 
    array(
     21, 
     22, 
     array(
      23, 
      array(
       52, 
       null 
       ) 
      ) 
     ) 
    ); 

$array_extracted = array(); 

array_walk_recursive($test_array, function($val, $key) use (&$array_extracted) {if (!is_array($val)) $array_extracted[] = $val;}); 

print_r($array_extracted); 
/* 
gives: Array 
(
    [0] => 20 
    [1] => 21 
    [2] => 22 
    [3] => 23 
    [4] => 52 
    [5] => 
) 
*/ 


1

此代碼應該這樣做:

function flatten_array($a) 
{ 
    $retval = array(); 
    foreach ($a as $value) 
    { 
     if (is_array($value)) 
      $retval = array_merge($retval,flatten_array($value)); 
     else 
      $retval []= $value; 
    } 
    return $retval; 
} 
+0

你忘了返回$ retval。 – RabidFire 2010-12-13 03:17:58

+0

你的「回報」在哪裏? – 2010-12-13 03:18:08

+0

哇!非常感謝。它真的有用! :) – rayss 2010-12-13 03:18:28