php 仅使用 Foreach 循环打印多维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5611483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:58:56  来源:igfitidea点击:

Printing a multi dimensional array using Foreach loop only

phparrays

提问by swapnesh

$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

区域 pandu nagar 和人位于 ravi

区域 pandu nagar 和人位于 ramesh

区域 pandu nagar 和人位于 sunil



Area sharda nagar and person located neeta

Area sharda nagar and person located meeta

Area sharda nagar and person located ritu

区域 sharda nagar 和人位于 neeta

区域 sharda nagar 和人位于 meeta

区域 sharda nagar 和人位于 ritu

回答by Pascal MARTIN

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.
  • 数组的第一维的一个循环,
  • 然后,第二个维度的一个循环——迭代从第一个维度获得的数据。

回答by Mohd Samiullah

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

回答by Vikas Kumar

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

best way to resolve this problem

解决此问题的最佳方法