php array iteration visually parent > child

2019-08-21 08:35发布

问题:

managed to create array tree with childs. Looks like this.

Want to try printing it out with same levels.

<ul>
<li>cat1</li>
<ul><li>sub-cat</li>
  <ul><li>subsub-cat</li>
    <ul><li>subsubsub-cat</li>
      <ul><li>subsubsubsub-cat</li></ul>
    <li>subcub-cat2</li>
<ul></ul></ul></ul></ul>
<li>cat2</li>
</ul>

Need to use iterative angle. At least point me to to the right direction.

It doesn't have to be with UL LI, can be with -- -- or some sort similar, just need to print it out using iterative methods.

回答1:

Try this piece of code:

<ul>
    <?php parse($array); ?>
</ul>
<?php
function parse($array) {
    foreach ($array as $value) {
        ?>
        <li><?php echo $value->name; ?>

            <?php if (!empty($value->child)) { ?>
                <ul>
                    <?php parse($value->child); ?>
                </ul>
            <?php } ?>
        </li>
        <?php
    }
}
?>

I've already faced this problem and used the same trick to handle.



回答2:

It is not the exact solution but you can use something like this

foreach( $array as $item ){
    echo $item['id'].'<br>';
    while(isset($item['child'])){
        $item = $item['child'];
        echo $item['id'].'<br>';
    }
}

here is the code sample that i generated http://sandbox.onlinephpfunctions.com/code/068f8b2d79cb5e210a6ee4c8e14c1a8649ab0dea