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.

  • Not a question. It is alarming that with this approach you will get wild enclosures of divs, since they first open up in each other, and at the end all are closed in turn - rjhdby
  • It is also a very dumb decision to unset an iterable array. In general, you have a wildest overdeveloped solution. It is better to describe what you want to get in the end, most likely you can decide much easier. - rjhdby
  • @rjhdby I need to put together a menu. The item comes with an object with which I collect it. Thanks, but I have already found a solution. Before the loop I write the following lines: <?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
  • @rjhdby It turns out I have already previously sifted extra. Thanks anyway for responding. - akim157

0