我没有得到以下PHP代码的所需输出

时间:2014-12-26 20:52:36

标签: php arrays foreach

我目前正处于学习阶段。

这是我的代码:

 <?php
    $food=array('Healthy'=>
                        array('Pasta'=>200,'Vegetables'=>300,'Salad'=>100), 

                'Unhealthy'=>
                        array('Pizza','Ice Cream'));
    foreach($food as $element =>$inner_array)   
        echo '<strong>'.$element.'</strong> <br>';
        foreach($inner_array as $inner_element)
        print_r ($inner_element.'<br>');
  ?>

我得到的输出:

Healthy 
Unhealthy 
Pizza
Ice Cream

我希望它显示与内部数组中元素相关的数字。

2 个答案:

答案 0 :(得分:4)

在两个foreach循环中都缺少括号,而在执行foreach之后只有第一行:

$food=array('Healthy'=> array('Pasta'=>200,'Vegetables'=>300,'Salad'=>100), 
            'Unhealthy'=> array('Pizza'=>0,'Ice Cream'=>1));

foreach($food as $element =>$inner_array) {  
    echo '<strong>'.$element.'</strong> <br>';
    foreach($inner_array as $inner_key => $inner_val) {
        print_r ($inner_val.'<br>');
    }
}

答案 1 :(得分:0)

<?php
    $food=array('Healthy'=> 
                            array('Pasta'=>200,'Vegetables'=>300,'Salad'=>100), 
                'Unhealthy'=> 
                            array('Pizza'=>500,'Ice Cream'=>350));     //Changes made here

    foreach($food as $element =>$inner_array) {

        echo '<strong>'.$element.'</strong> <br>';

    foreach($inner_array as $inner_key => $inner_val)    //Changes made here

        print_r ("$inner_key => $inner_val <br>");       //Changes made here

        }
    ?>

这给出了我期待的输出。