swapnesh
swapnesh

Reputation: 26732

Printing a multi dimensional array using Foreach loop only

$info = array(
    "pandu nagar"  => array("ravi","ramesh","sunil"),
    "sharda nagar" => array("neeta","meeta","ritu")
);

I want to print output like-

Area pandu nagar and person located ravi

Area pandu nagar and person located ramesh

Area pandu nagar and person located sunil


Area sharda nagar and person located neeta

Area sharda nagar and person located meeta

Area sharda nagar and person located ritu

Upvotes: 5

Views: 32579

Answers (3)

Vikas Kumar
Vikas Kumar

Reputation: 21

foreach ($info as $key => $values) {   
    foreach ($values as $anotherkey => $val) {
        echo 'key:'.$key. ' AnotherKey: '.$anotherkey.' value:'.$val.'<br>';
    }
}

best way to resolve this problem

Upvotes: 1

Mohammed Samiullah
Mohammed Samiullah

Reputation: 175

And for printing array with one more index name:

$info = array (
    "00500" => array( "0101" => "603", "0102" => "3103", "0103" => "2022"),
    "01300" => array( "0102" => "589", "0103" => "55"),
    "02900" => array( "0101" => "700", "0102" => "3692", "0103" => "2077")
); 

You can do this:

foreach ($info as $key => $values) {

    foreach ($values as $anotherkey => $val) {
        echo 'key:'.$key. ' AnotherKey: '.$anotherkey.' value:'.$val.'<br>';
    }

}

output will be:

key:00500 AnotherKey: 0101 value:603 
key:00500 AnotherKey: 0102 value:3103 
key:00500 AnotherKey: 0103 value:2022 
key:01300 AnotherKey: 0102 value:589 
key:01300 AnotherKey: 0103 value:55 
key:02900 AnotherKey: 0101 value:700 
key:02900 AnotherKey: 0102 value:3692 
key:02900 AnotherKey: 0103 value:2077

Upvotes: 2

Pascal MARTIN
Pascal MARTIN

Reputation: 400972

What about this :

foreach ($info as $name => $locations) {
    foreach ($locations as $location) {
        echo "Area {$name} and person located {$location}<br />";
    }
}

Which means :

  • One loop for the first dimension of the array,
  • and, then, one loop for the second dimension -- iterating over the data gotten from the first one.

Upvotes: 11

Related Questions