如何使用foreach回显数组数组?

时间:2012-07-17 03:35:33

标签: php arrays foreach

我正在尝试自动化我的导航链接。如何自动回显foreach。我现在正在获取未定义的偏移量......我可以忽略数组中的第一项(即标题)吗?

'control' => array( 0=>'Controls',
                    1=> array('Add school','add.school.php'),
                    2=> array('Add doctor','add.doctor.php'),
                    3=> array('Add playgroup','add.play.php'),
                    4=> array('Suggestions','suggestion.php'),
                    5=> array('List tutor service','list.tutor.php'),
                    6=> array('Create playgroup','create.play.php'),
                        7=> array('Dashboard', 'dashboard.php')
                        ),



 <?php  

    foreach ($nav['control'] as $value=>$key){
                echo'<a href="'.$key[2].'">'.$key[1].'</a>';
                }
   ?>

4 个答案:

答案 0 :(得分:4)

数字数组的索引编号为0而不是1.您分别需要[1][0]

答案 1 :(得分:2)

// for key => value is more nature.
foreach ($nav['control'] as $key => $value){
   // should skip the first.
   if ($key === 0) {
     continue;
   }
   // array is 0 base indexed.
   echo'<a href="'.$value[1].'">'.$value[0].'</a>';
}

答案 2 :(得分:0)

foreach ($nav['control'] as $value=>$key) {
                echo'<a href="'.$key[1].'">'.$key[0].'</a>';
}

答案 3 :(得分:0)

嵌套数组需要嵌套循环。

foreach($array as $key => $value){
  if($key != 0){
  foreach($value as $k => $v){
    if($k == 0){ $title = $v;}
    if($k == 1){ $link = $v;}
  }
//put code to run for each entry here (i.e. <div> tags, echo $title and $link)
}

我个人的做法,当我只使用两个字段时,将第一个推入数组['id'],将第二个推入数值,即

while($row_links = sth->fetch (PDO::FETCH_ASSOC)){
  $array[$row_links['title']] = $row_links['link'];
}

然后你可以使用

<?php foreach($array as $key => $value){ ?>
  <a href="<?php echo $value; ?>"><?php echo $key; ?></a>
<?php } ?>