简体   繁体   中英

How to echo the key:value pairs of a sub array? PHP

I'm having trouble pulling out the key value pairs in only one sub array of a two dimensional array. I'm trying to get it in the following format:

"Insect: b: beetle
 Insect: m: moth
 etc..."

here is what I've got so far:

$animals = array(
'insect'    =>  array('b'=>"beetle", 'm'=>"moth", 's'=>"spider"),
'mammal'    =>  array('d'=>"dolphin", 'h'=>"human", 'c'=>"chimp"),
'fish'      =>  array('a'=>"angler", 'sh'=>"shark", 'p'=>"puffer"));
echo $animals['insect']; // trying to print sub array??
echo "<pre>";
foreach($animals as $Mkey => $domains)
    foreach($domains as $key => $species)
        echo "$Mkey: $key : $species<br>"; //prints whole array
foreach($animals['insect'] as $Mkey => $species) {
    echo "$Mkey : $species<br>";
}

// dynamic key:    
$key = 'insect';
foreach($animals[$key] as $Mkey => $species) {
    echo "$key: $Mkey : $species<br>";
}

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