简体   繁体   中英

Loop into a multidimensional array in PHP

I have this array in PHP:

array( 
    "name" => "Cherry", 
    "desc" => "I'm a cherry.",
    "keys" => array(
            "Africa",
            "India",
            "America"
    ),
    "pict" => "image1.png",
)

And I want to loop into this and between keys to display to countries/continents.

This is what I have already tried:

foreach($details as $detail) {
    foreach($keys as $key) {
        echo $key;
    }
}

In case if you want to get other values in array along with countries:

<?php

$details = array( 
    "name" => "Cherry", 
    "desc" => "I'm a cherry.",
    "keys" => array(
            "Africa",
            "India",
            "America"
    ),
    "pict" => "image1.png",
);


foreach( $details as $key => $detail ) {

    if( is_array( $detail ) && $key == 'keys' ) {

        foreach( $detail as $country ) {
            echo $country;
        }

    } else {

        echo $detail;
    }
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM