Home > Article > Backend Development > How to Access First Level Keys of a 2D Array using a Foreach Loop in PHP?
Using a Foreach Loop to Access First Level Keys of a 2D Array
In this situation, you can utilize the PHP foreach loop with the correct syntax to effectively access the first level keys of your 2D array, $places.
The updated code below incorporates the proper syntax for extracting the first level keys:
<?php foreach ($places as $key => $site): ?> <h5><?= $key ?></h5> <!-- Replace key($site) with $key --> <?php foreach($site as $place): ?> <h6><?= $place['place_name'] ?></h6> <?php endforeach ?> <?php endforeach ?>
By revising the line where you retrieve the first level key, you now use the variable $key instead of key($site). This change directly accesses the first level key (in this case, the name of the city) and assigns it to the $key variable. Consequently, you can effortlessly display the first-level key (the city name) within your view.
The above is the detailed content of How to Access First Level Keys of a 2D Array using a Foreach Loop in PHP?. For more information, please follow other related articles on the PHP Chinese website!