user3723240
user3723240

Reputation: 393

PHP data in array repeats inside for each

I have an array like so:

Array(
    [Ancaster] => Array(
        [AncasterGlen] => Array(
            [0] => 43.2057, -79.9632,
            1, -70, -150[1] => 140664277023ancaster - glen . jpg[2] => 19[3] => 0
        ) [AncasterGlenPhase2] => Array(
            [0] => [1] => [2] => 21[3] => 1
        ) [AncasterWoodlands] => Array(
            [0] => [1] => 140674933154woodlands - courts . png[2] => 23[3] => 1
        )
    ) [Hamilton] => Array(
        [HighlandRoad] => Array(
            [0] => [1] => [2] => 22[3] => 1
        )
    )
)

and in my code, I am going through each item to display each title (Ancaster and Hamilton) and under each title, display the subtitle where [3] is equal to 1 (For Ancaster - AncasterGlenPhase2 and AncasterWoodlands and For Hamilton - HighlandRoad) but for some reason, the title Ancaster repeats itself :( this happened when I added AncasterWoodlands

here is my code (the array above is $pages):

<?php
foreach($pages as $row => $value){
    foreach($value as $key => $name){
        if($name[3] == 0){
            continue;
        }
        echo '<li>' . $row . '<ul>';
        foreach($value as $x => $y){
            if($y[3] == 0){
                continue;
            }
            echo '<li><a href="our-communities.php?subpage=registerupcoming&newcommunity=' . str_replace(" ", "", strtolower($y[2])) . '" title="' . $x . '">' . $x  . '</a></li>';
        }
        echo '</li></ul>';
    }
}
?>

What am I doing wrong?

Upvotes: 0

Views: 52

Answers (1)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41820

You do not need the outer foreach loop. That is what is causing the duplication. All you should need is this part:

foreach ($pages as $row => $value) {
    echo '<li>' . $row . '<ul>';
    foreach ($value as $x => $y) {
        if ($y[3] == 0) {
            continue;
        }
        echo '<li><a href="our-communities.php?subpage=registerupcoming&newcommunity=' 
         . str_replace(" ", "", strtolower($y[2])) . '" title="' . $x . '">' . $x  
         . '</a></li>';
    }
    echo '</li></ul>';
}

Upvotes: 1

Related Questions