php array iteration visually parent > child

对着背影说爱祢 提交于 2020-01-06 08:32:17

问题


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



来源:https://stackoverflow.com/questions/50680550/php-array-iteration-visually-parent-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!