Using a Foreach Loop to Retrieve First Level Keys in a 2D Array
In PHP, iterating through a multidimensional array can be tricky, especially when it comes to accessing its first level keys. Let's delve into a practical scenario and demonstrate how to achieve this using a foreach loop.
You have an array named $places with a structure like this:
[Philadelphia] => Array ( [0] => Array ( [place_name] => XYX [place_id] => 103200 [place_status] => 0 ) [1] => Array ( [place_name] => YYYY [place_id] => 232323 [place_status] => 0 ) )
Your code currently looks like this:
foreach($places as $site): ?> <h5><?=key($site)?></h5> <?php foreach($site as $place): ?> <h6><?=$place['place_name']?></h6> <?php endforeach?> <?php endforeach ?>
You aim to retrieve the first level key (e.g., "Philadelphia") when you call key($site), but it's currently returning the second level key ("place_name").
To resolve this issue, you need to access the first level key directly, which is straightforward in PHP:
foreach ($places as $key => $value)
In this code, $key will be the first level key, and $value will represent the corresponding array for that key.
Here's a revised code:
foreach ($places as $key => $site): ?> <h5><?= $key ?></h5> <?php foreach($site as $place): ?> <h6><?=$place['place_name']?></h6> <?php endforeach?> <?php endforeach ?>
The above is the detailed content of How to Retrieve First Level Keys in a 2D Array Using a Foreach Loop in PHP?. For more information, please follow other related articles on the PHP Chinese website!