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
Release: 2024-11-09 20:54:02
Original
1013 people have browsed it

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template