2016-02-24 79 views
0

從多維數組中獲取數組中所有數據的正確方法是什麼?在多維數組中返回數組數據的正確方法?

Array 
(
[0]Array 
    (
     [0] Array 
      (
       [day] 3/1/2016 
       [start1] 12:15am 
       [end1] 1:15am 
       [start2] 
       [end2] 
      ) 

     [1] Array 
      (
       [day] 3/2/2016 
       [start1] 12:00am 
       [end1] 1:00am 
       [start2] 
       [end2] 
      ) 

     [2] Array 
      (
       [day] 3/3/2016 
       [start1] 12:00am 
       [end1] 12:00am 
       [start2] 
       [end2] 
      ) 

    ) 

) 

我想遍歷並獲取每個嵌套數組的所有信息,但我似乎遇到未定義的索引錯誤。

foreach($timeArray as $day){ 
echo "Day: " + $day['day'] + "Start1: " + $day['start1'] + "End1: " + $day['end1'] + "Start2: " + $day['start2'] +"End2: " + $day['end2']; 
} 
+0

對不起,我讓我的JS和PHP現在混在一起。需要睡眠大聲笑 – tai

回答

0

如果$timeArray是整個陣列,然後

  • $timeArray[0]是它下面的陣列,其具有所有的日子
  • $timeArray[0][0]是它下面的陣列,這是第一個元素第一天
  • $timeArray[0][0]["day"]包含值3/1/2016

另一個需要注意的是,你被錯誤地串聯的字符串:

  • "Text " + $variable + " Text" =錯誤
  • "Text $variable Text" =右
  • "Text {$variable["key"]} Text" =也對

所以每天訪問:

foreach($timeArray[0] as $day){ 
    echo "Day: {$day['day']}", 
     "Start1: {$day['start1']}", 
     "End1: {$day['end1']}", 
     "Start2: {$day['start2']}", 
     "End2: {$day['end2']}"; 
} 

參考:

+0

謝謝你的解釋和參考。絕對有助於爲我解決問題。 – tai

0

看起來你數組有2升evels,假設你的例子是你的陣列的全部內容,這會工作

而且在PHP中連接字符是.,而不是+

foreach($timeArray[0] as $day){ 
    echo "Day: " . $day['day'] . 
     "Start1: " . $day['start1'] . 
     "End1: " . $day['end1'] . 
     "Start2: " . $day['start2'] . 
     "End2: " . $day['end2']; 
} 

你也可以利用這個事實的雙引號的字符串將擴大變量這樣

foreach($timeArray[0] as $day){ 
    echo "Day: {$day['day']} Start1: {$day['start1']} End1: {$day['end1']} "; 
    echo "Start2: {$day['start2']} End2: {$day['end2']}"; 
} 

或者,如果你不引用數組名

foreach($timeArray[0] as $day){ 
    echo "Day: $day[day] Start1: $day[start1] End1: $day[end1] "; 
    echo "Start2: $day[start2]} End2: $day[end2]"; 
} 
0

你可以通過這個閱讀您的陣列:

foreach ($your_arr as $key_internal=>$arr_internal){ 
     foreach ($arr_internal as $key=>$value){ 
      echo $value['day']; 
      ...... 
     } 
}