每个人!
我一直在尝试编写递归函数。=( 这是我的函数,正如我所料,它将我的普通数组变成多维数组。
function BuildTree($src, $index=0) {
foreach ($src as $index=>$curentItem) {
$nextItem = (is_array($src[$index+1]))?$src[$index+1]:false;
unset($src[$index]);
if ($nextItem['d']==$curentItem['d']) $brunchArray[] = $curentItem['n'];
if ($nextItem['d']>$curentItem['d']) $brunchArray['childrens'] = BuildTree($src, $index);
if (!$nextItem || $nextItem['d']<$curentItem['d']) return $brunchArray;
}
}
输入数组是这样的:
$input = array (
array(
'n' => 'Articles',
'd' => 0
),
array(
'n' => 'Article 1',
'd' => 1
),
array(
'n' => 'Books',
'd' => 0
),
array(
'n' => 'Book 1',
'd' => 1
),
array(
'n' => 'Book 2',
'd' => 1
),
array(
'n' => 'Chapter 1',
'd' => 2
),
array(
'n' => 'Chapter 2',
'd' => 2
)
);
我希望它被转换成这个:
array (
array(
'n' => 'Articles',
'd' => 0,
'childrens' => array (
array(
'n' => 'Article 1',
'd' => 1
),
)
),
array(
'n' => 'Books',
'd' => 0,
'childrens' => array (
array(
'n' => 'Book 1',
'd' => 1
),
array(
'n' => 'Book 2',
'd' => 1
'childrens' => array (
array(
'n' => 'Chapter 1',
'd' => 2
),
array(
'n' => 'Chapter 2',
'd' => 2
)
)
)
)
)
)
我已经花了三个小时试图解决这个问题。=( 任何帮助将不胜感激!