2012-04-18 44 views
0

我要嵌套另一個數組裏的數組的數組循環,我的代碼將類似於此通過內部另一個陣列的PHP

array(
'type' => 'FeatureCollection', 
'features' => array(
    array(
     'type' => 'Feature', 
     'geometry' => array(
      'coordinates' => array(-94.34885, 39.35757), 
      'type' => 'Point' 
     ), // geometry 
     'properties' => array(
      // latitude, longitude, id etc. 
     ) // properties 
    ), // end of first feature 
    array(...), // etc. 
) // features 
) 

當外部部分(特徵)封裝了許多其它陣列。我需要循環從已經解碼的json文件中提取的變量 - 我將如何循環訪問這些數據集? A foreach()

+1

簡短的回答是:是的。 – Tadeck 2012-04-18 00:38:19

+0

@Tadeck,很高興知道我在正確的軌道上。 :) – 2012-04-18 00:43:09

回答

0

嵌套的foreach。

$myData = array(array(1, 2, 3), array('A', 'B', 'C')) 

foreach($myData as $child) 
    foreach($child as $val) 
    print $val; 

將打印123ABC。

+1

應至少使用OP示例數據。 – 2012-04-18 00:42:03

+0

那麼,如果我想讓它像1A,2A,3A那樣呢? – 2012-04-18 00:57:31

+1

對於一個簡單的例子,OP的數據太混亂了。 :) 去1A2B3C有點難,但你可以這樣做: foreach($ myData [0]作爲$ key => $ val)print $ myData [0] [$ key]。$ myData [1] [ $關鍵] – DanRedux 2012-04-18 01:05:05

2

你知道陣列的孩子的深度嗎?如果你知道深度總是保持不變?如果對這兩個問題的回答是肯定的,那麼foreach應該這樣做。

$values = array(
'type' => 'FeatureCollection', 
'features' => array(
    array(
     'type' => 'Feature', 
     'geometry' => array(
      'coordinates' => array(-94.34885, 39.35757), 
      'type' => 'Point' 
     ), // geometry 
     'properties' => array(
      // latitude, longitude, id etc. 
     ) // properties 
    ), // end of first feature 
    array('..'), // etc. 
) // features 
); 

foreach($values as $value) 
{ 
    if(is_array($value)) { 
     foreach ($value as $childValue) { 
      //.... continues on 
     } 
    } 
} 

但如果任何這兩個問題的答案是否定的,我會用一個遞歸函數用foreach,像這樣一起。

public function myrecursive($values) { 
    foreach($values as $value) 
    { 
     if(is_array($value)) { 
      myrecursive($value); 
     } 
    } 
}