Sujan Shrestha
Sujan Shrestha

Reputation: 1040

Simple Foreach loop with tricky situation

I found this problem quite challenging.I have a foreach loop which looks like this.

<ul class="menu">
<li class="menu1"><a href="#"><?php echo $records[0]['olt_name'] ?></a>
        <ul class="menu">
            <?php
            $unique = array();
            foreach($records as $r)
            {
                $a = substr($r['pon_port'],2,1);
                if(!in_array($a, $unique)) {
                    $unique[] = $a;
                    echo '<li class="menu1"><a href="#">' . $a . '</a>'; //slots
                }

             ------->>>>>> echo '<ul class="menu">';
echo'<li class="menu1"><a href="#">'.substr($r['pon_port'],4,1).'</a></li>';

                        echo '</ul>';
            }

            echo '</li>';
            ?>
        </ul>
</li>
</ul>

What I want to achieve is a list item like this:

<ul>
<li><a href="#"> Level 1 </a>
<ul>
<li><a href="#"> Level 1.1 </a>
    <ul>
    <li><a href="#"> Level 1.1.1 </a></li>
    <li><a href="#"> Level 1.1.2 </a></li>
    <li><a href="#"> Level 1.1.3 </a></li>
    <li><a href="#"> Level 1.1.4 </a></li>
    </ul>
</li>
</ul>

Now i facing a tricky situation. The start of <ul> which i have shown arrow is looping each time because of foreach. So every time loop runs it goes like this:

<ul><li></li><ul> 
<ul><li></li><ul>

i dont want <ul></ul> to loop every time. Is there a way to enter the <ul> once and the donot enter next time the loop runs. only enter <li> each time loop runs.

This is dump of $records.

array(24) { [0]=> array(2) { ["pon_port"]=> string(5) "0/0/4" ["olt_name"]=> string(8) "BRT-OLT1" } 
[1]=> array(2) { ["pon_port"]=> string(5) "0/0/3" ["olt_name"]=> string(8) "BRT-OLT1" } 
[2]=> array(2) { ["pon_port"]=> string(5) "0/0/1" ["olt_name"]=> string(8) "BRT-OLT1" } 
[3]=> array(2) { ["pon_port"]=> string(5) "0/0/5" ["olt_name"]=> string(8) "BRT-OLT1" } 
[4]=> array(2) { ["pon_port"]=> string(5) "0/0/2" ["olt_name"]=> string(8) "BRT-OLT1" } 
[5]=> array(2) { ["pon_port"]=> string(5) "0/0/6" ["olt_name"]=> string(8) "BRT-OLT1" } [6]=> array(2) { ["pon_port"]=> string(5) "0/0/7" ["olt_name"]=> string(8) "BRT-OLT1" } 

Upvotes: 2

Views: 90

Answers (1)

Barmar
Barmar

Reputation: 780974

Use a variable to indicate whether it's the first time through the loop.

$unique = array();
$first = true;
foreach ($records as $r) {
    $a = substr($r['pon_port'],2,1);
    if(!in_array($a, $unique)) {
        $unique[] = $a;
        echo '<li class="menu1"><a href="#">' . $a . '</a></li>'; //slots
    }
    if ($first) {
        echo "<ul>";
        $first = false;
    }
    echo'<li class="menu1"><a href="#">'.substr($r['pon_port'],4,1).'</a></li>';
}
if (!$first) {
    echo "</ul>";
}

DEMO

Upvotes: 2

Related Questions