MrLearner
MrLearner

Reputation: 141

How to display values from an array which is both indexed and multidimensional?

I know how to display values from an indexed array and multidimensional array separately (using foreach) but I cant make it work when it is a combination of both.

Im creating a two-level navigation menu using an array structured like this:

$pages = array(
    'home',
    'about' => array(
        'label' => 'Who We Are',
        'children' => array(
            'company',
            'team'
        ),
    ),
);

When I use a foreach with key-value pair

foreach ($pages as $page => $value){
    echo $page; // output:    0  about
    echo $value; // output:    home  array
}

And without the key-value pair:

foreach ($pages as $page){
    echo $page; // output:    home  array  array
}

I'd just like for the output to be

Home    Who We Are

Can someone point me to the right direction?

Thanks in advance!

Upvotes: 0

Views: 38

Answers (3)

Ropali Munshi
Ropali Munshi

Reputation: 3026

You can use a recursive function to loop through that array, Use this code.

function loop($arr){

  foreach($arr as $val){
      if (is_array($val)) {
         loop($val);  
      }
      else {
       echo $val . '<br>';      
      }

  }

}

$pages = array(
    'home',
    'about' => array(
        'label' => 'Who We Are',
        'children' => array(
            'company',
            'team'
        ),
    ),
);

loop($pages);

Upvotes: 0

sabbir chowdury
sabbir chowdury

Reputation: 158

<?php
$pages = array(
'home',
'about' => array(
    'label' => 'Who We Are',
    'children' => array(
        'company',
        'team'
    ),
),

);

foreach($pages as $key =>$page){
if(!is_array($page)){
    echo $page;
}
}
if(is_array($pages['about'])){
foreach($pages['about'] as $about){
    if(!is_array($about)){
        echo " ".$about;
    }
}
}

if(is_array($pages['about']['children'])){
foreach ($pages['about']['children'] as $child){
    if(!is_array($child)){
        echo " ".$child;
    }
}
}

?>

Upvotes: 0

Using is_array function is a trick. You code like this

$pages = array(
    'home',
    'about' => array(
        'label' => 'Who We Are',
        'children' => array(
            'company',
            'team'
        ),
    ),
);
foreach($pages as $key=>$value){
    if(is_array($value)){
        echo $value["label"];
    }else{
        echo $value;
    }
}

Upvotes: 1

Related Questions