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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-05 19:43:02284browse

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

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

When working with a two-dimensional array, you may want to access the first level keys in a loop. To achieve this, you can utilize the following approach:

Consider the following $places array:

<code class="php">[Philadelphia] => Array
        (
            [0] => Array
                (
                    [place_name] => XYX
                    [place_id] => 103200
                    [place_status] => 0
                )

            [1] => Array
                (
                [place_name] => YYYY
                [place_id] => 232323
                [place_status] => 0
            )
        )</code>

In the provided view code, you have a foreach loop that loops over the array's second level keys. To access the first level keys (e.g., "Philadelphia"), you can modify the loop as follows:

<code class="php"><?php foreach ($places as $key => $site): ?>
    <h5><?= $key ?></h5>
    <?php foreach ($site as $place): ?>
        <h6><?= $place['place_name'] ?></h6>
    <?php endforeach ?>
<?php endforeach ?></code>

By using $key => $site in the outer loop, you can access the first level keys as $key and iterate through the second level keys as $site. This modification will allow you to retrieve the "Philadelphia" key in your example.

The above is the detailed content of How to Access First Level Keys of a 2D Array using 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