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

How to Retrieve First Level Keys in a 2D Array Using a Foreach Loop in PHP?

Mary-Kate Olsen
Release: 2024-11-04 20:22:02
Original
254 people have browsed it

How to Retrieve First Level Keys in a 2D Array Using a Foreach Loop in PHP?

Using a Foreach Loop to Retrieve First Level Keys in a 2D Array

In PHP, iterating through a multidimensional array can be tricky, especially when it comes to accessing its first level keys. Let's delve into a practical scenario and demonstrate how to achieve this using a foreach loop.

You have an array named $places with a structure like this:

[Philadelphia] => Array
    (
        [0] => Array
            (
                [place_name] => XYX
                [place_id] => 103200
                [place_status] => 0
            )

        [1] => Array
            (
            [place_name] => YYYY
            [place_id] => 232323
            [place_status] => 0
        )
    )
Copy after login

Your code currently looks like this:

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

<?php endforeach ?>
Copy after login

You aim to retrieve the first level key (e.g., "Philadelphia") when you call key($site), but it's currently returning the second level key ("place_name").

To resolve this issue, you need to access the first level key directly, which is straightforward in PHP:

foreach ($places as $key => $value)
Copy after login

In this code, $key will be the first level key, and $value will represent the corresponding array for that key.

Here's a revised code:

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

<?php endforeach ?>
Copy after login

The above is the detailed content of How to Retrieve First Level Keys in 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