0

我正在尝试自动化我的导航链接。如何自动回显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

4 回答 4

4

数字数组从 0 开始索引,而不是 1。你想要[1][0]分别。

于 2012-07-17T03:37:22.333 回答
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>';
}
于 2012-07-17T03:39:29.743 回答
0
foreach ($nav['control'] as $value=>$key) {
                echo'<a href="'.$key[1].'">'.$key[0].'</a>';
}
于 2012-07-17T03:38:31.257 回答
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 } ?>
于 2012-07-17T03:50:26.707 回答