我有一個只讀的多維關聯數組,我需要從中提取特定值以生成具有某些值的輸出。使用php列出多維數組中的特定鍵/值
陣列看起來像這樣:
array (
'Dogs' =>
array (
0 =>
array (
'Name' => 'Big Dogs',
'ID' => '32',
'Brown dogs' =>
array (
0 =>
array (
'Name' => '4 legged dogs',
'Retrievers' =>
array (
0 =>
array (
'Name' => 'Fido',
'ID' => '11',
'Owner' => 'Billy',
'IsaBiter' => true,
),
),
),
1 =>
array (
'Name' => '3 legged dogs',
'Retrievers' =>
array (
0 =>
array (
'Name' => 'Spot',
'ID' => '12',
'Owner' => 'Sally',
'IsaBiter' => false,
),
),
),
等。
這通過可打印陣列的所有值如下所述陣列運行的嵌套foreach循環:
echo "<ul>";
foreach($myArray as $arr1 => $val1) {
foreach($val1 as $arr2 => $val2) {
foreach($val2 as $val3) {
echo "<li>" . $val3 . "<ul>";
foreach($val3 as $arr4 => $val4) {
foreach($val4 as $arr5 => $val5) {
echo "<li>" . $val5;
foreach($val5 as $arr6 => $val6) {
//echo $val6;
foreach($val6 as $arr7 => $val7) {
echo $val7 . "<br />"; //dumps the details
}
echo "</li>";
}
}
}
echo "</ul>";
echo "</li>";
}
}
}
理想情況下,我希望能夠1)排除我不想顯示的值(ID,某些數組級別名稱等,目前顯示全部)和2)顯示特定的值(即Name,Owner,IsaBiter)我可以格式化結果更清晰,類似於此:
Big Dogs
Brown Dogs
Retrievers
Name: Fido
Owner: Billy
IsaBiter: true
Name: Spot
Owner: Sally
IsaBiter: false
你應該爲此使用遞歸。 –
當你使用foreach($ array AS $ key => $ value){}時,你可以比較$ key和你想要顯示的內容(它只是一個字符串)。無論如何,過濾一個級別會更加複雜,您應該包含一個迭代器值(一個整數計數級別)並在正確時排除。也許,正如@WayneWhitty所說,使用遞歸會更好。 –
感謝您的評論,但我爲什麼要這麼做? – bridgemanusa