dongqian2021 2014-01-14 07:56
浏览 248
已采纳

使用foreach循环同时循环通过两个多维数组

i am trying to loop through two multi-dimensional array with a foreach loop

[array1] => Array ( 
[0] => Array ( 1,2,3 ) 
[1] => Array ( 4,5,6 ) 
[2] => Array ( 7,8,9 )
  )
[array2] => Array ( 
[0] => Array ( 1,2,3 ) 
[1] => Array ( 4,5,6 ) 
[2] => Array ( 7,8,9 ) ) 
  )

both has same keys,

i want to access 1st array of both arrays at same time, i want to do something like this

foreach($array1 as $key1=>$value1 && $array2 as $key2=>$value2)
    echo $value1[1]."  ".$value2[2]

its not correct, but that's what i want to do !!

  • 写回答

3条回答 默认 最新

  • douzhi3105 2014-01-14 08:01
    关注

    If the keys are identical between the two arrays in both dimensions :

    foreach (array_keys($array1) as $key1) {
        foreach (array_keys($array1[$key1]) as $key2) {
            echo $array1[$key1][$key2].' '.$array2[$key1][$key2];
        }
    }
    

    Worst case scenario, some keys in one dimension or the other are missing in one or both arrays and you have to merge them prior to reading (and ensure the existence of the key's value in each loop & array).


    UPDATE: used the same solution twice for two-dimensional array structure.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?