|  | Posted by Tamagafk on 04/12/07 08:00 
Hi! Looks like there is a bug in php. If I have function which usesforeach to run trough array recursively, the lop-level foreach
 interupted by lover-level foreach'es. If I use simply 'for' everything
 is ok. Example:
 
 I have an array of 3 objects connected hierarchically by their
 variables id and parentId, here is the  hierarchy:
 id=1 parentId=0
 ....id=2 parentId=1
 ....id=3 parentId=1
 
 I start digging from item with id=1 down to its chils and top-level
 foreach NEVER REACH ELEMENT 3!!! Top-level foreach just stops.
 
 <?php
 function prn($s){
 echo($s.'<br>');
 }
 
 $nodes = array();
 $nodes[0] = new node(1, 0);
 $nodes[1] = new node(2, 1);
 $nodes[2] = new node(3, 1);
 $nodes[3] = new node(4, 0);
 
 class	node{
 var $id;
 var $parentId;
 
 function node($id, $parentId){
 $this->id = $id;
 $this->parentId = $parentId;
 }
 
 function dig($level){
 global $nodes;
 
 $l = '';
 for($i=0; $i<$level; $i++) $l.='..';
 prn($l.'looking for childs of '.$this->id.' {');
 
 foreach($nodes as $n){
 prn($l.$n->id.' (parent '.$n->parentId.')');
 if($n->parentId == $this->id){
 $n->dig($level+1);
 }
 }
 
 prn($l.'}');
 }
 
 }
 
 $nodes[0]->dig(0);
 
 ?>
 
 The output should look like this:
 
 looking for childs of 1 {
 1 (parent 0)
 2 (parent 1)
 ...looking for childs of 2 {
 ...1 (parent 0)
 ...2 (parent 1)
 ...3 (parent 1)
 ...}
 3 (parent 1)
 ...looking for childs of 3 {
 ...1 (parent 0)
 ...2 (parent 1)
 ...3 (parent 1)
 ...}
 }
 
 But it looks like this:
 
 looking for childs of 1 {
 1 (parent 0)
 2 (parent 1)
 ...looking for childs of 2 {
 ...1 (parent 0)
 ...2 (parent 1)
 ...3 (parent 1)
 ...}
 }
 [Back to original message] |