Home > Backend Development > PHP Tutorial > How to Access First Level Keys of a 2D Array using a Foreach Loop in PHP?

How to Access First Level Keys of a 2D Array using a Foreach Loop in PHP?

Susan Sarandon
Release: 2024-11-05 01:58:02
Original
201 people have browsed it

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 ?>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template