2017-08-08 71 views
1

我有一個陣列的多層次如何排列的多關鍵字合併到單一陣列

$array = array("14529" => array("900" => array("87" => array()))); 

print_r(array_keys($array)); // result array("14529"); 

如何這個數組合併到單一陣列

$array = array("14529", "900", "87"); 
+1

你檢查了這個鏈接嗎https://stackoverflow.com/questions/11234852/how-to-get-all-the-key-in-multi-dimensional-array-in-php –

+2

你試過什麼嗎? –

+0

您是否忘記將此問題設置爲已回答? – GregaMohorko

回答

3

這裏是一個函數,你想要做什麼。它是以遞歸方式完成的,因此數組的深度並不重要。

function mergeArrayMultiKeyToSingleArray($array, $result=[]) 
{ 
    foreach($array as $key => $value) { 
     $result[] = $key; 
     if(is_array($value)) { 
      $result = mergeArrayMultiKeyToSingleArray($value, $result); 
     } 
    } 

    return $result; 
} 

// USAGE: 
$array = array("14529" => array("900" => array("87" => array()))); 
$array = mergeArrayMultiKeyToSingleArray($array); 
// $array is now ["14529", "900", "87"] 
+1

美麗的解決方案。 – Ali

0

我沒有使用RecursiveIteratorIterator類使用這個類

class ArrayStripper 
{ 
    private $items = []; 

    public function strip($arrayOrItem) 
    { 
     if(is_array($arrayOrItem)) 
     { 
      foreach ($arrayOrItem as $item) 
      { 
       $this->strip($item); 
      } 
     } 
     else 
     { 
      $this->items[] = $arrayOrItem; 
     } 
    } 

    public function get() 
    { 
     return $this->items; 
    } 
} 

$array = [1 , [2,3] , 4 , [[5 , 6 , 7] , [8 ,9] , 10]]; 
$stripper = new ArrayStripper(); 
$stripper->strip($array); 
var_dump($stripper->get()); 
1

解決辦法:

$arr = ["14529" => ["900" => ["87" => [] ] ] ]; 
$keys = []; 
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($arr), RecursiveIteratorIterator::SELF_FIRST) as $k => $v) { 
    $keys[] = $k; 
} 

print_r($keys); 

輸出:

Array 
(
    [0] => 14529 
    [1] => 900 
    [2] => 87 
)