<?php $n=0; function data($parent_id, $robots2, $n, $type_id) { $n++; foreach ($robots2 as $robot): if ($robot->parent_id==$parent_id): ?> <p style = "margin-left:<?php echo 1+$n;?>%"><?php echo $robot->name;?></p> <?php data($robot->id, $robots2, $n, $type_id); ?> <?php endif; endforeach; $n--; } ?> 

Further full nesting of the first element is not. those. Element 1 Element 1.1. Element 1.1.1 And Element 2, etc. are not displayed. Tell me, good people, what to do ...

  • Foreach does not complete the previous iteration after it has completed the nested one. How to continue it? - Artem
  • The algorithm is working, apparently an error in the method of iterating over the contents of the object. On the array, everything works well. I will smoke a manual by phalcon - Artem

2 answers 2

 $n=0; function data($parent_id, $robots2, $n, $type_id) { $n++; // здесь 1 foreach ($robots2 as $robot): if ($robot->parent_id==$parent_id):?> <p style = "margin-left:<?php echo 1+$n;?>%"><?php echo $robot->name;?></p> <?php data($robot->id, $robots2, $n, $type_id); ?> <?php endif; endforeach; $n--; // здесь опять 0 } 
  • Well, yes, each launch of the function - an offset to the right by 1%, if there are no investments, then the next position is identical to the previous one (without tabulation) - Artem

Stop interfering with HTML and PHP so there are formatting functions (printf / sprintf).

  1. Removed unnecessary increments / increments.
  2. Cleaned up the mess in the code.
  3. Added test data.

PS: to phalcon irrelevant.

 <?php function data($parent_id, $robots2, $n, $type_id) { foreach ($robots2 as $robot) { if ($robot->parent_id==$parent_id) { printf( // %% - escaped %. '<p style = "margin-left:%s%%">%s</p>%s', $n + 2, $robot->name, // New line constant PHP_EOL ); data($robot->id, $robots2, $n + 1, $type_id); } }; } // Test data $robots = [ (object)['id' => 1, 'parent_id' => 0, 'name'=> 'r 1'], (object)['id' => 2, 'parent_id' => 0, 'name'=> 'r 2'], (object)['id' => 3, 'parent_id' => 1, 'name'=> 'r 3'], (object)['id' => 4, 'parent_id' => 2, 'name'=> 'r 4'], (object)['id' => 5, 'parent_id' => 1, 'name'=> 'r 5'], (object)['id' => 6, 'parent_id' => 3, 'name'=> 'r 6'], ]; data(0, $robots, 0, 1); //var_dump($robots);