多维foreach数组仅返回最后一次迭代

时间:2012-11-13 20:10:23

标签: php

我正在尝试格式化数据,以便我的json代码可以正确读取它。最终结果需要如下所示:

[2][4][36] = 'Ohio'

其中'2'是区域id,'4'是分区id,'36'是状态id。显然,根据选择的区域和区域有很多不同的结果,但所有结果都需要按照上面的方式返回。

我从下面的代码得到的结果只返回最后一次迭代。我想知道我做错了什么:

$divisionCodeResults = array();
    foreach($regionCodes as $key => $value){        
       $divisionCodeResults[$key] = $divisionTable->getDivisionResultsByRegionCode($key);                
            foreach($divisionCodeResults as $divValue){
                $array_1 = array();
                foreach($divValue as $divKey => $div2Value){                    
                    $array_1[$divKey] = $divKey;   
                    $array_2 = array();
                    foreach($array_1 as $array_1_value){                        
                        $array_2[$key][$divKey] = Doctrine_Core::getTable('state')->getStatesIdAndNamesThatMatchDivisionKey($array_1_value);
                    }
                }
           }
    }

上面的var_dump()输出以下内容:

array (size=1)
  6 => 
    array (size=1)
      11 => 
        array (size=2)
          52 => string 'Puerto Rico' (length=11)
          54 => string 'Virgin Islands' (length=14)

格式正确,但如上所述,它只返回长多维数组中的最后一次迭代。

希望能够解释我做错了什么......先谢谢。

编辑:

array (size=5)
  2 => 
    array (size=2)
      4 => string 'East North Central' (length=18)
      5 => string 'West North Central' (length=18)
  3 => 
    array (size=2)
      2 => string 'New England' (length=11)
      3 => string 'Mid-Atlantic' (length=12)
  4 => 
    array (size=3)
      6 => string 'South Atlantic' (length=14)
      7 => string 'East South Central' (length=18)
      8 => string 'West South Central' (length=18)
  5 => 
    array (size=2)
      9 => string 'Mountain' (length=8)
      10 => string 'Pacific' (length=7)
  6 => 
    array (size=1)
      11 => string 'Carribean' (length=9)

以上结果为:var_dump($ divisionCodeResults);

1 个答案:

答案 0 :(得分:0)

将$ array_1和$ array_2移到循环之外,例如:

$array_1 = array();
$array_2 = array();
$divisionCodeResults = array();
foreach($regionCodes as $key => $value){        
    $divisionCodeResults[$key] = $divisionTable->getDivisionResultsByRegionCode($key);                
        foreach($divisionCodeResults as $divValue){
//                $array_1 = array();
            foreach($divValue as $divKey => $div2Value){                    
                $array_1[$divKey] = $divKey;   
//                    $array_2 = array();
                foreach($array_1 as $array_1_value){                        
                    $array_2[$key][$divKey] = Doctrine_Core::getTable('state')->getStatesIdAndNamesThatMatchDivisionKey($array_1_value);
                }
            }
        }
}