2016-08-12 119 views
0

這是一個簡單的數組。我想要取得所有雙親&孩子。我怎樣才能得到?如何在PHP中獲取樹型數組的所有元素?

$tree = array (
    1 => array (
      2 => "A", 
      3 => "B", 
      4 => array (
        6 => "D", 
        7 => array (
          8 => "E", 
          9 => array (
            10 => "F", 
            11 => "G" 
          ) 
        ) 
      ), 

      5 => "C" 
    ) 

);

+1

寫遞歸功能?! – Rizier123

+0

@ Rizier123你能解釋一下如何編寫遞歸函數嗎? –

+0

也給出預期的輸出還有 – Dan

回答

1

下面是模式密鑰1個值A鍵3值B鍵4值d,E,F的答案,G鍵5值C

$tree = array (
    1 => array (
      2 => "A", 
      3 => "B", 
      4 => array (
        6 => "D", 
        7 => array (
          8 => "E", 
          9 => array (
            10 => "F", 
            11 => "G" 
          ) 
        ) 
      ), 

      5 => "C" 
    ) 
); 

// Loop through $tree array 
// Since you are assigning array to index 1, 
// Use $tree[1] instead of just $tree 
foreach($tree[1] as $key => $value) 
{ 
    // Pring key 
    echo "Key {$key}: "; 

    // Check key value type is array or not 
    if (gettype($value) == 'array') 
    { 
     // if it's array data type call recursive function 
     print_array($value); 
    } 
    else 
    { 
     // just pring value 
     echo "{$value}, "; 
    } 
    echo "\n"; 
} 

// Recursive function 
// Takes array as parameter 
function print_array(array $array) 
{ 
    // Loop through associative array in the form of key and value 
    foreach($array as $key => $value) 
    { 
     // If the value is array data type or not 
     if (gettype($value) != 'array') 
     { 
      // if true, just print the value 
      echo "$value"; 
     } 
     else 
     { 
      // call recursive function 
      print_array($value); 
     } 
    } 
} 
+0

這項工作適合我。非常感謝。 –

1

使用遞歸函數

$tree = array (
    1 => array (
      2 => "A", 
      3 => "B", 
      4 => array (
        6 => "D", 
        7 => array (
          8 => "E", 
          9 => array (
            10 => "F", 
            11 => "G" 
          ) 
        ) 
      ), 

      5 => "C" 
    ) 
); 

// Recursive function 
// Take array as parameter 
function print_array(array $array) 
{ 
    // Loop through associative array in the form of key and value 
    foreach($array as $key => $value) 
    { 
     // If the value is array data type call recursive function 
     // by passing the value itself 
     if (gettype($value) == 'array') 
     { 
      echo "New array of Key:{$key} started <br>"; 
      print_array($value); 
     } 
     else 
     { 
      // If the value is not array just print it 
      echo "Key: {$key}, Value {$value} <br>"; 
     } 
    } 
} 

print_array($tree); 
+0

我不擅長英文,所以我的解釋可能會變得複雜。我想要所有的父母和孩子的價值。例如.. 鑰匙1有1個小孩 鍵4具有6子 於是出放我想是, 鍵1個值A 鍵3值B 鍵4值d,E,F,G 鍵5值C –

+0

@NyeinChan我已經發布了你所要求的模式中的另一個答案。 –

相關問題