存取陣列中的元素可能很棘手,尤其是在處理多維數組時。讓我們解決嘗試從包含巢狀數組的多維數組中檢索值時面臨的常見問題。
考慮以下多維數組:
$array = [ [ 'id' => 1, 'name' => 'Bradeley Hall Pool', // ... other properties ], [ 'id' => 2, 'name' => 'Farm Pool', // ... other properties 'suitability' => [ // A nested array [ 'fk_species_id' => 4, 'species_name' => 'Barbel', // ... other properties ] ], ] ];
目標是存取嵌套適宜性中的species_name屬性array.
$speciesName = $array[1]['suitability'][0]['species_name'];
foreach ($array as $topLevelArray) { if (isset($topLevelArray['suitability'])) { foreach ($topLevelArray['suitability'] as $suitabilityItem) { echo $suitabilityItem['species_name'] . PHP_EOL; } } }
以上是如何存取嵌套 PHP 數組中的值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!