2011-05-22 198 views
1

在這裏有關於multidim數組和foreach循環的很多問題/答案,但我還沒有找到一個專門適用於我的情況的問題/答案。請告知,如果你認爲否則。PHP - foreach循環和多維數組

我的陣列被如下構造,並且被輸出到一個笨視圖:

Array 
(
    [2] => Array //this is the unique user ID 
     (
      [name] => Joe Schmoe 
      [cars] => Array 
       (
        [112] => Array //this is the unique car ID 
         (
          [cars_name] => Honda 
          [cars_type] => Sedan 
          [cars_color] => White 
         ) 

        [102] => Array 
         (
          [cars_name] => Toyota 
          [cars_type] => Sedan 
          [cars_color] => Black 
         ) 

        [113] => Array 
         (
          [cars_name] => Nissan 
          [cars_type] => Coupe 
          [cars_color] => Red 
         ) 
       ) 
     ) 

    [5] => Array 
     (
      [name] => Buck 
      [cars] => Array 
       (
        [147] => Array 
         (
          [cars_name] => Tesla 
          [cars_type] => Sedan 
          [cars_color] => Yellow 
         ) 
       ) 
     ) 

    [1] => Array 
     (
      [name] => Mike Mechanic 
      [cars] => Array 
       (
        [140] => Array 
         (
          [cars_name] => BMW 
          [cars_type] => SUV 
          [cars_color] => Blue 
         ) 

        [145] => Array 
         (
          [cars_name] => MB 
          [cars_type] => Sedan 
          [cars_color] => Gray 
         ) 

       ) 
     ) 
) 

我需要幫助構建嵌套foreach循環,所以我可以訪問整個陣列中的元素中的每一個。

我試過這個嵌套的foreach結構,但它是不行的。

foreach ($results as $data): 
    if (is_array($data)): 
     foreach ($data as $value): 
      if (is_array($value)): 
       foreach ($value as $row): 
       endforeach; 
      endif; 
     endforeach; 
    endif; 
endforeach; 

echo $row->cars_name //returns a non-object error 

任何人都知道如何把這個嵌套循環放在一起?

感謝您的幫助,非常感謝。

+0

爲什麼這是一個不行? – GolezTrol 2011-05-22 15:53:51

+0

我試着在嘗試回顯數組元素時嘗試獲取非對象錯誤的屬性 – pepe 2011-05-22 15:56:52

+1

這是因爲它不是對象,而且您的行爲就像它一樣。請參閱我的答案中的編輯。 – GolezTrol 2011-05-22 15:59:19

回答

2

您正在訪問循環外的$ row。如果你想處理每一行,你應該把這個代碼(echo)放到循環中。

另一種方法是使用array_walk_recursive。這將爲多維數組中的每個值調用回調函數。

你得到的行也不是一個對象。它仍然是一個數組。嘗試

echo $row['cars_name']; 
+0

感謝您的評論@ goleztrol - 我試過內循環,仍然得到相同的'試圖獲得非對象的屬性錯誤 - – pepe 2011-05-22 15:59:11

+0

@torr'echo $ row ['cars_name'] ;'而不是'echo $ row-> cars_name' – 2011-05-22 16:14:51

+0

謝謝@goleztrol&@Luc M - 工作很棒 – pepe 2011-05-23 02:43:09

1

我認爲這會爲你工作..

foreach ($results as $result) { 
    if(is_array($result['cars'])){ 
     foreach ($result['cars'] as $car) { 
      echo $car['cars_name']; 
     } 
    } 
} 

你也試圖通過訪問類屬性訪問符號數組元素。