function printItem($item, &$items, $childrens, $active) { if(count($items) == 0) return; echo '<div><a'.(in_array($item->id, $active)?'class="active "':'') .($item->external?'rel="external "':'') .'href="'.$item->link.'">'.$item->title.'</a>'; while(true) { $key = array_search($item->id, $childrens); if(!$key) break; unset($childrens[$key]); printItem($items[$key], $items, $childrens, $active) } echo '</div>'; unset($items[$item->id]); } ?> <div id="menu"> <div class="menu"> <?php foreach($items as $item) printItem($item, $items, $childrens, $active) ?> </div> </div>
On items comes an array of the following form:
Array ( [1] => MenuDB Object ( [format_date:AbstractObjectDB:private] => %d.%m.%Y %H:%M:%S [id:AbstractObjectDB:private] => 1 [properties:AbstractObjectDB:private] => Array ( [type] => Array ( [value] => 1 [validator] => ValidateID [type] => ) [title] => Array ( [value] => Меню1 [validator] => ValidateTitle [type] => ) [link] => Array ( [value] => # [validator] => ValidateURL [type] => ) [parent_id] => Array ( [value] => [validator] => ValidateID [type] => ) [external] => Array ( [value] => 0 [validator] => ValidateBoolean [type] => ) ) [table_name:protected] => menu ) ...
The problem is the following: if recursion goes, then items as a reference variable must be overwritten, however, during the second iteration of the loop, the element is taken 2, although after recursion it should be 14, because 2 must be removed. If you call items inside a loop before calling a function, you can see that items during the second iteration starts at position 14, i.e. the function worked correctly, however, when the second iteration occurs, the function receives 2 elements from the items, although it must be removed because porridge occurs. How to solve this problem? Thank.
<?php $reshit = array(); ?> <?php foreach($items as $k=>$v) { ?> <?php if($v->parent_id == 0 && !isset($reshit[$k])) $reshit[$k] = $v; ?> <?php } ?>
<?php $reshit = array(); ?> <?php foreach($items as $k=>$v) { ?> <?php if($v->parent_id == 0 && !isset($reshit[$k])) $reshit[$k] = $v; ?> <?php } ?>
<?php $reshit = array(); ?> <?php foreach($items as $k=>$v) { ?> <?php if($v->parent_id == 0 && !isset($reshit[$k])) $reshit[$k] = $v; ?> <?php } ?>
- akim157