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

How to Access First Level Keys of a 2D Array Using a Foreach Loop?

DDD
DDDOriginal
2024-11-09 20:54:021019browse

How to Access First Level Keys of a 2D Array Using a Foreach Loop?

Accessing the First Level Keys of a 2D Array Using a Foreach Loop

To obtain the city names in the $places array, you can access the first level keys. A straightforward method is through a foreach loop.

In your PHP code:

<code class="php">foreach ($places as $city => $sites) {
    echo "<h5>{$city}</h5>";

    foreach ($sites as $site) {
        echo "<h6>{$site['place_name']}</h6>";
    }
}</code>

This code iterates over the keys of the outer array, which are the city names. Within the inner loop, it accesses the first level keys as $city. By using =>, you assign both the key and value to the corresponding variables, allowing you to access the city name directly as $city.

The above is the detailed content of How to Access First Level Keys of a 2D Array Using a Foreach Loop?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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