1

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

3 Answers 3

2

Use the & operator:

$array[$id_child]['parent'] = &$array[$id_parent];

and also:

$array[$id_parent]['children'][] = &$array[$id_child];
Sign up to request clarification or add additional context in comments.

1 Comment

I can't tell where you should put it unless you provide me with the rest of your code. In the two lines above, $array is the array you provided in the question, $id_child and $id_parent are the array keys, respectively, of a child and of a parent (i.e. $array[$id_child] is a child of $array[$id_parent], and vice versa the latter is the parent of the former).
0
a[59]['IdParent'] = a[59]['ID'];

doesn't that work as per your question ?

Comments

0
// 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;
}

2 Comments

adding some description along with your answer is nice
Tank you for your advice. Because my english is so so. So it's very hard for me. But I will try my best to do it when i am free.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.