2013-03-07 80 views
0

如何通過遞歸將一個數組轉換爲其他數組?這個例子僅適用於第二級。如何做遞歸?

$array2 = array(); 
foreach ($array as $levelKey => $level) { 
    foreach ($level as $itemKey => $item) { 
    if (isset($array[$levelKey + 1])) { 
     $array2[$item['data']['id']] = $item; 
     $children = $this->searchChildren($item['data']['id'], $array[$levelKey + 1]); 
     $array += $children; 
    }    
    } 
} 

function searchChildren($parent_id, $level) 
{ 
    $_children = array(); 
    foreach ($level as $key => $item) { 
    if ($item['data']['parent_id'] === $parent_id) { 
     $_children[$key] = $item; 
    } 
    } 
    return $_children; 
} 
+1

你必須自己調用你的函數...... – crush 2013-03-07 14:28:56

+4

爲了理解遞歸,你必須瞭解遞歸。 – ddinchev 2013-03-07 14:29:08

+0

當你在我的例子中顯示它? – tomasr 2013-03-07 14:30:31

回答

0

下面是一個遞歸使用一個簡單的例子。此功能遞歸打印所有項目的級聯鍵和值數組中

function printArrayWithKeys(array $input, $prefix = null) { 
    foreach ($input as $key=>$value) { 
     $concatenatedKey = $prefix . '.' . $key; 
     if (is_array($value)) { 
      printArrayWithKeys($value, $concatenatedKey); 
     } else { 
      print $concatenatedKey . ': ' . $value . "\n"; 
     } 
    } 
} 

這一功能的關鍵是它自稱爲,當它遇到另一個數組(因此繼續遍歷的各級陣列)

您可以輸入如叫它:

array(
    array(
     array('Hello', 'Goodbye'), 
     array('Again') 
    ), 
    'And Again' 
) 

凡將打印:

0.0.0: Hello 
0.0.1: Goodbye 
0.1.0: Again 
1: And Again