user1187135
user1187135

Reputation:

how do I echo out an array array using foreach?

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

Upvotes: 0

Views: 396

Answers (4)

Lee Bishop
Lee Bishop

Reputation: 16

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

Upvotes: 0

xdazz
xdazz

Reputation: 160833

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

Upvotes: 2

Paul Denisevich
Paul Denisevich

Reputation: 2414

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

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

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

Upvotes: 4

Related Questions