PHP获取多维数组的值并进行比较



我有这个数组$pages,它吐出了这个数据:

Array ( 
    [Name] => Array ( 
        [Subname] => Array ( 
            [0] => 43.2057, -79.9632, 1, -70,-150 
            [1] => 140240757658.jpg 
            [2] => 5 
            [3] => 0 
        ) ) 
    [Name2] => Array ( 
        [Subname2] => Array ( 
            [0] => 43.1769, -79.4703, 5, -70,-150 
            [1] => 140267498933.png 
            [2] => 16 
            [3] => 0 
        ) ) 
)

,我有这样的设置:

foreach($pages as $row => $value) {
    echo '<li>'.$row.'<ul>';
    foreach($value as $x => $y) {
        echo 
            '<li>
                <a href="page.php?" action='.str_replace(" ", "", strtolower($y[2])).'" title="'.$x.'">'.$x.'</a>
             </li></ul></li>';
    }
}

我想做的是,如果每个Subname中的[3]等于0,那么从我的foreach中跳过它。

注意:Subname和Name只是例子,它们会有所不同

应该可以:

foreach ($pages as $page) {
    foreach($page as $subname) {
        if ($subname[3] != 0) {
            /* Do whatever you want with the data of this subname */
        } 
    }
}

如果你想使用键名,可以这样:

foreach ($pages as $pageKey => $page) {
    foreach($page as $subnameKey => $subname) {
        if ($subname[3] != 0) {
            /* Do whatever you want with the data of this subname */
        } 
    }
}

如果您想跳过子foreach,那么这就是解决方案

foreach($pages as $row => $value) {
    if($value['Subname'][3] == 0)
        continue;
    echo '<li>' . $row . '<ul>';
    foreach($value as $x => $y) {
        echo '<li><a href="page.php?action=' . str_replace(" ", "", strtolower($y[2])) . '" title="' . $x . '">' . $x  . '</a></li></ul></li>';
    }
}

由于这是一个关联数组,您将无法检查

$pages['foo']['bar'][0] === 0

之前开始第一个foreach,因为事先不知道 $pages['foo']的值。当我们到达检查点时你已经输出了HTML格式为:

 echo '<li>' . $row . '<ul>';

相关内容

  • 没有找到相关文章

最新更新