如何在遍历多维数组时访问键和第一个字符串值?

时间:2017-08-23 22:15:08

标签: php loops multidimensional-array

期望的结果:"我喜欢的咸食是小吃Rufles"。 我想回应阵列"零食"在阵列内"咸食"作为一个字符串:

$food = array(
    "salty food" => array(
        "snack" => array(
            0 => "Rufles",
            1 => "Generic"
        )
    )
);

echo "My prefered ";

foreach($food as $key => $value)     //salty food
    echo $key;

echo " is the ";

//--MY DOUBT IS HERE. DESIRED ECHO: "snack" (FROM THE DEEP ARRAY):
foreach($food as $key => $value)
    echo $key["snack"];

print_r($food["salty food"]["snack"][0]);     //Rufles

2 个答案:

答案 0 :(得分:1)

使用嵌套循环:

echo "My preferred ";
foreach ($food as $type1 => $value1) {
    echo $type1;
    echo " is the ";
    foreach ($value1 as $type2 => $value2) {
        echo "$type2 $value2[0]";
    }
}

DEMO

答案 1 :(得分:0)

应该没问题

<?php 

    $food = array(
        "salty food" => array(
            "snack" => array(
                0 => "Rufles",
                1 => "Generic"
                )
            )
    );

    echo "My prefered ";

    foreach($food as $key1 => $value){
        echo $key1;    
        echo " is the ";        
        foreach($value as $key2 => $value){
            echo $key2." ";
        }        
    }    
    print_r($food["salty food"]["snack"][0]);


?>