Вопрос

I need build tree hierarchy through recursion. All working fine without php unset, but I want unset elements which already been built.

Problem: In code below unset working, but break the first recursion call, so from the example data category where id=5 not rendering.

Any ideas, very interesting what's wrong

 function renderMenu(&$tempTree, $parentId){
        foreach($tempTree as $row) {
            if ($row['parent_id'] == $parentId) {
                $id = $row["category_id"];
                echo $row['name'].'<br>';
                unset($tempTree[$id]);
               if (isset($row['has_child'])){
                   renderMenu($tempTree, $id);
                }

            }
        }
    }

$s=array ( '1' => Array ( 'category_id' => 1,
'parent_id' => 0,
'name' => '1' ),

'2' => Array ( 'category_id' => 2,
'parent_id' => 0,
'has_child' => true,
'name' => '2'),

'3' => Array ( 'category_id' => 3,
'parent_id' => 2,
'name' => '3'),

'4' => Array ( 'category_id' => 4,
'parent_id' => 2,
'name' => '4'),

'5' => Array ( 'category_id' => 5,
'parent_id' => 0,
'name' => '5' )
);



renderMenu($s,0);
Это было полезно?

Решение

The error is here:

 unset($tempTree[$id]);

It should be:

 unset($row[$id]);

(As your in a foreach loop referencing $tempTree elements as $row)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top