2013-03-07 62 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