2014-01-20 135 views
0

我查了一堆類似的例子,但似乎無法弄清楚如何通過循環並回顯這個數組中的值。應該很簡單,但我很密集。幫助表示讚賞。在PHP中循環遍歷多維數組

array(2) { ["legend_size"]=> int(1) ["data"]=> array(2) { ["series"]=> array(2) { [0]=> string(10) "2014-01-17" [1]=> string(10) "2014-01-18" } ["values"]=> array(1) { ["Begin Session"]=> array(2) { ["2014-01-17"]=> int(1073) ["2014-01-18"]=> int(1122) } } } } 

我想返回「值」數組的int值。

+0

你試過遞歸與類型檢查?這可能會有所幫助:http://stackoverflow.com/questions/15917022/looping-through-a-multi-dimensional-array –

+0

@ josh-austin你可以從問題本身告訴我,我很新手,所以遞歸是現在脫離我的聯盟。 –

回答

1

鑑於你數組的名字,例如,$mdarr的緣故,和該陣列的建設將是大約每一次一樣,它是那樣簡單:

$values_i_want = $mdarr['data']['values']; 

如果您正在尋找將是在不同情況下的不同陣列的深度值陣列,用遞歸類型檢查相結合,將這樣的伎倆:

//returns values array or nothing if it's not found 
function get_values_array($mdarr) { 
    foreach ($mdarr as $key => $val) { 
     if ($key == 'values') { 
      return $val; 
     } else if (is_array($val)) { 
      return get_values_array($val); 
     } 
    } 
} 
0

以下列爲基礎。我重建了你的陣列,所以我可以搞砸它。

$turtle = array('legend_size' => 'int(1)', 'data' =>array('series' => array('string(10) "2014-01-17"', '[1]=> string(10) "2014-01-18"'), 'values' => array('Begin_Session' =>array('2014-01-17' => 'int(1073)', '2014-01-18' => 'int(1122)')))); 

// This is where you "navigate" the array by using [''] for each new array you'd like to traverse. Not sure that makes much sense, but should be clear from example. 
foreach ($turtle['data']['values']['Begin_Session'] as $value) { 
    $match = array(); 
// This is if you only want what's in the parentheses. 
    preg_match('#\((.*?)\)#', $value, $match); 
    echo $match[1] . "<br>"; 
} 
0

如果數組S tructure是不會改變,只是想和你裏面values整型值,你可以做到以下幾點:

//Create array 
$some_array = array( 
    "legend_size" => 5, 
    "data" => array( 
     "series" => array(0 => "2014-01-17", 1 => "2014-01-18") 
     "values" => array(
      "Begin Session" => array("2014-01-17" => 1000, "2014-01-18" => 1000) 
     ) 
    ) 
); 

//Get values 
foreach($some_array['data']['values'] as $key => $value) 
{ 
    if(is_array($value)) 
    { 
     echo $key . " => "; 

     foreach($value as $key2 => $value2) 
     { 
      echo " " . $key2 . " => " . $value2; 
     } 
    } 

    else 
    { 
     echo $key . " => " . $value; 
    } 
} 

這會給你這樣的輸出:

Begin Session => 
    2014-01-17 => 1000 
    2014-01-18 => 1000