我有一个带有“ levels”的数组,如下所示:
Array
[0] => Array
(
[level] => 0
[header] => First h2
)
[1] => Array
(
[level] => 1
[header] => First h3
)
[2] => Array
(
[level] => 1
[header] => Second h3
)
[3] => Array
(
[level] => 2
[header] => First h4
)
[4] => Array
(
[level] => 2
[header] => Second h4
)
[5] => Array
(
[level] => 2
[header] => Again h4
)
[6] => Array
(
[level] => 1
[header] => Once again h3
)
[7] => Array
(
[level] => 2
[header] => New h4
)
[8] => Array
(
[level] => 0
[header] => End
)
我正在尝试获得像这样的多维数组:
[0] => Array
(
[level] => 0
[header] => First h2
[childs] => Array
(
[0] => Array
(
[level] => 1
[header] => First h3
)
[1] => Array
(
[level] => 1
[header] => Second h3
[childs] => Array
(
[0] => Array
(
[level] => 2
[header] => First h4
)
[1] => Array
(
[level] => 2
[header] => Second h4
)
[2] => Array
(
[level] => 2
[header] => Again h4
)
)
)
[2] => Array
(
[level] => 1
[header] => Once again h3
[childs] => Array
(
[0] => Array
(
[level] => 2
[header] => New h4
)
)
)
)
)
[1] => Array
(
[level] => 0
[header] => End
)
我的功能是:
function generateFromHeaders(array $headers)
{
$newArr = [];
$level1 = 1;
for ($i = 0; $i <= count($headers); $i++) {
$currentLevel = $headers[$i]['level'];
if ($currentLevel === 0) {
$newArr[] = $headers[$i];
} elseif ($currentLevel === 1) {
$newArr[$i-$level1]['childs'][] = $headers[$i];
} elseif ($currentLevel === 2) {
$childs =& $newArr[$i-$level1]['childs'];
$childs[count($childs)-1]['childs'][] = $headers[$i];
} elseif ($currentLevel === 3) {
$childs =& $newArr[$i-$level1]['childs'];
$count = count($childs[count($childs)-1]['childs']);
$childs[count($childs)-1]['childs'][$count-1]['childs'][] = $headers[$i];
} elseif ($currentLevel === 4) {
$childs =& $newArr[$i-$level1]['childs'];
$subChilds =& $childs[count($childs)-1]['childs'];
$subChilds1 =& $subChilds[count($subChilds)-1]['childs'];
$subChilds1[count($subChilds1) - 1]['childs'][] = $headers[$i];
}
$level1 = $currentLevel > 0 ? $level1 + 1 : 1;
}
return $newArr;
}
传递的数组中的最大级别为4,因此不需要递归,但是我不喜欢这个难看的代码。 如您所见,数组元素的层次越深,找到子子代等的最新子子代所需的代码就越多。
也许会有更好的算法将简单数组转换为多维数组?