数组中的PHP数据在每个内部重复

时间:2014-07-30 19:55:26

标签: php arrays

我有一个像这样的数组:

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
        )
    )
)

在我的代码中,我将浏览每个项目以显示每个标题(Ancaster和Hamilton),并在每个标题下显示[3]等于1的副标题(对于Ancaster - AncasterGlenPhase2和AncasterWoodlands以及For Hamilton - HighlandRoad)但由于某种原因,标题Ancaster重演:(这发生在我加入AncasterWoodlands时

这是我的代码(上面的数组是$ 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>';
    }
}
?>

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您不需要外部foreach循环。这就是造成重复的原因。你应该需要的就是这部分:

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>';
}