问题
I have a little problem with a recursion in php. I have read many articles but the solution doesn't come.
I have this array:
[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
)
I would like to create a hierarchical tree where the IdParent field match with the ID field.
Does anybody help me?
thanks
回答1:
Use the & operator:
$array[$id_child]['parent'] = &$array[$id_parent];
and also:
$array[$id_parent]['children'][] = &$array[$id_child];
回答2:
a[59]['IdParent'] = a[59]['ID'];
doesn't that work as per your question ?
回答3:
// 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;
}
来源:https://stackoverflow.com/questions/4931080/php-recursion-how-to-create-a-recursion-in-php