在這裏有關於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
任何人都知道如何把這個嵌套循環放在一起?
感謝您的幫助,非常感謝。
爲什麼這是一個不行? – GolezTrol 2011-05-22 15:53:51
我試着在嘗試回顯數組元素時嘗試獲取非對象錯誤的屬性 – pepe 2011-05-22 15:56:52
這是因爲它不是對象,而且您的行爲就像它一樣。請參閱我的答案中的編輯。 – GolezTrol 2011-05-22 15:59:19