1

Is there a more elegant way to output the given html structure with an array? I found some recursive solutions but therefore a parent_id is needed (if I understand correctly).

HTML

<ul>
  <li>Level 1</li>
  <li>
    <ul>
      <li>Level 2</li>
      <li>
        <ul>
          <li>Level 3</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

Array

Array
(
[0] => Level 1
[1] => Array
    (
        [0] => Level 2
        [1] => Array
            (
                [0] => Level 3
            )

    )

)

Loops

<ul>
<?php foreach($array as $arr) : ?>
    <li>
    <?php if(is_array($arr)) : ?>
        <ul>
            <?php foreach($arr as $a) : ?>
                <li>
                <?php if(is_array($a)) : ?>
                    <ul>
                        <?php foreach($a as $aa) : ?>
                            <li><?php echo $aa; ?></li>
                        <?php endforeach; ?>
                    </ul>
                <?php else : ?>
                    <?php echo $a; ?>
                <?php endif; ?>
                </li>
            <?php endforeach; ?>
        </ul>
    <?php else : ?>
        <?php echo $arr; ?>
    <?php endif; ?>
    </li>
<?php endforeach; ?>
</ul>

I´m a bit worried about the performance of this approach :-D

3
  • 1
    Why don't use echo for the HTML tags as well? Commented Feb 25, 2015 at 0:57
  • why don't you check performance yourself? Commented Feb 25, 2015 at 0:58
  • I think readability is a bigger concern than performance there. It looks like one of those optical illusions. Commented Feb 25, 2015 at 1:02

1 Answer 1

2

do it just recursive:

<?PHP

function doOutputList($TreeArray)
{
    echo '<ul>';
    foreach($TreeArray as $arr)
    {
        echo '<li>';
        if(is_array($arr)) 
        {
                doOutputList($arr);
        }
        else
        {
                echo $arr;
        }
        echo '</li>';
    }
    echo '</ul>';
}

doOutputList($array);

?>

Or if you like good readable HTML Code try this:

<?PHP

function doOutputList($TreeArray, $deep=0)
{
    $padding = str_repeat('  ', $deep*3);

    echo $padding . "<ul>\n";
    foreach($TreeArray as $arr)
    {
        echo $padding . "  <li>\n";
        if(is_array($arr)) 
        {
                doOutputList($arr, $deep+1);
        }
        else
        {
                echo $padding .'    '. $arr;
        }
        echo $padding . "  </li>\n";
    }
    echo $padding . "</ul>\n";
}

doOutputList($array);

?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.