2011-04-10 72 views
5
$info = array(
    "pandu nagar" => array("ravi","ramesh","sunil"), 
    "sharda nagar" => array("neeta","meeta","ritu") 
); 

我想打印输出喜欢 -打印使用的foreach循环仅

区潘渡格尔和人位于拉维

区潘渡格尔和人位于拉梅什

一多维数组面积pandu nagar和人位于sunil


区SHARDA格尔和人位于neeta

区SHARDA格尔和人位于meeta

区SHARDA格尔和人位于日图

回答

11

这个怎么样:

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

表示:

  • 一个循环用于第一维数组,
  • 然后,第二维的一个循环 - 迭代从第一维获取的数据。
+0

感谢帕斯卡多数民众赞成在工作正常:) – swapnesh 2011-04-10 11:41:00

+0

不客气:-) – 2011-04-10 11:43:41

2

而对于多一个索引名打印阵列:

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

你可以这样做:

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

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

} 

输出将是:

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 
+0

这真的很清楚它应该是没有1个答案 – 2016-01-31 05:20:05

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

最好方法来解决橄榄此问题