Home >Backend Development >PHP Tutorial >How can I access first-level keys of a 2D array using a foreach loop?

How can I access first-level keys of a 2D array using a foreach loop?

Susan Sarandon
Susan SarandonOriginal
2024-11-06 13:28:02360browse

How can I access first-level keys of a 2D array using a foreach loop?

Access First-Level Keys of a 2D Array with a Foreach Loop

To retrieve the first-level keys of a multidimensional array using a foreach loop, you can employ the following syntax:

<code class="php">foreach ($array as $key => $value)</code>

Consider the following example:

<code class="php">$places = [
    'Philadelphia' => [
        [
            'place_name' => 'XYZ',
            'place_id' => 103200,
            'place_status' => 0,
        ],
        [
            'place_name' => 'YYYY',
            'place_id' => 232323,
            'place_status' => 0,
        ],
    ]
];

foreach ($places as $siteKey => $site) {
    echo "City: $siteKey" . PHP_EOL;  // Philadelphia

    foreach ($site as $place) {
        echo "\tPlace Name: {$place['place_name']}" . PHP_EOL;
    }
}</code>

In this code, the $places array contains a two-dimensional structure representing cities (Philadelphia) and their associated places. The outer foreach loop iterates over the first-level keys (cities), accessing both the keys (Philadelphia) and the values ($site in this case). Within each $site, the inner loop iterates over the second-level keys (places) and accesses their values, displaying the 'place_name' field.

The above is the detailed content of How can I 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