我在php中的递归有点问题。我读了很多文章,但解决方案没有。
我有这个数组:
[59] => Array
(
[ID] => REL000000
[Name] => RELIGIONE / Generale
[Description] =>
[IdParent] =>
)
[799] => Array
(
[ID] => REL102000
[Name] => RELIGIONE / Teologia
[Description] =>
[IdParent] => REL000000
)
[800] => Array
(
[ID] => REL068000
[Name] => RELIGIONE / Teosofia
[Description] =>
[IdParent] => REL000000
)
[801] => Array
(
[ID] => REL103000
[Name] => RELIGIONE / Universalismo Unitario
[Description] =>
[IdParent] => REL000000
)
[802] => Array
(
[ID] => REL034000
[Name] => RELIGIONE / Festività / Generale
[Description] =>
[IdParent] => REL000000
)
我想创建一个分层树,其中IdParent字段与ID字段匹配。
有人帮帮我吗?
谢谢
使用&
运算符:
$array[$id_child]['parent'] = &$array[$id_parent];
并且:
$array[$id_parent]['children'][] = &$array[$id_child];
a[59]['IdParent'] = a[59]['ID'];
根据你的问题,这不起作用吗?
// There is a function maybe useful
/**
* get all sub
*
* @author Tom
* @date 2017-12-21
* @param array $array The array
* @param int|str $topId the the top ID
* @param int $lev the the lev(It's ver useful in some case)
* @return array $result all sub data
*/
function getLower($array, $topId, $lev = 0) {
$result = [];
foreach ($array as $key => $value) {
if ($value['IdParent'] == $topId) {
$value['lev'] = $lev; // the level
$result[] = $value;
$result = array_merge($result, getLower($array, $value['ID'], $lev + 1));
}
}
return $result;
}