Recursive enumeration data DB foreach

Hello! Do DB hierarchy . The problem is this: after working a nested foreach function is no longer to do the previous crawl , eventually process ends on the last nesting level of the first

$robots2 = Data::find();
<?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--;
    }
    ?>
edited Aug '16
<?php

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