0

i am trying to automate my navigation links. How do I automatically echo out foreach. I am getting undefined offset right now... And can I ignore the first item in the array (i.e. title)?

'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 Answers 4

4

Numeric arrays are indexed from 0, not 1. You want [1] and [0] respectively.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

1 Comment

A brief explanation of numeric indices would make this +1 worthy
0

a nested array requires nested loop.

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

my personal practice when i only use two fields is to push the first into the array['id'] and the second as the value i.e.

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

then you can use

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

1 Comment

Please check out my edit to see how to format code and text separately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.