无法在foreach中检索数组键

时间:2015-01-05 03:09:25

标签: php arrays

我已经在阵列中循环了数百次,但我今天一定要发疯了,因为我得到了不希望的结果。

我已将所有信息存储在我的$ data变量中,print_r显示以下内容

Array
(
[side_orders] => Array
    (
        [white_rice] => Array
            (
                [price] => Array
                    (
                        [0] => 0.50
                    )
            )
    )

[soup] => Array
    (
        [wonton_soup] => Array
            (
                [price] => Array
                    (
                        [0] => (pt)2.00
                        [1] => (qt)3.75
                    )
            )
    )

[steamed_dishes] => Array
    (
        [vegetarian] => Array
            (
                [info] => snow_peas
                [price] => Array
                    (
                        [0] => 4.95
                    )
             )
     )

   )

我正在尝试展示side_orders,soup,steamed_dishes'

所以我然后使用以下内容进行测试。

             foreach($data as $dat)
             {
                 echo key($data);
             }

返回' side_ordersside_ordersside_orders'

知道我做错了吗?

1 个答案:

答案 0 :(得分:0)

<?php
$array=array(
"side_orders" => 
array("white_rice" => 
array("price" => array("0" => "0.50"))
),
"soup" => 
array("wonton_soup" =>
array("price" => array("0" => "(pt)2.00", "1" => "(qt)3.75")))
);
///// Display Array /////
print_r($array);
////////////////////////
$side_orders_price_0 = $array['side_orders']['white_rice']['price']['0'];
$soup_price_0 = $array['soup']['wonton_soup']['price']['0'];
$soup_price_1 = $array['soup']['wonton_soup']['price']['1'];

echo '</br>(side_orders -> white_rice -> price -> 0) = '.$side_orders_price_0.' </br>';
echo '(soup -> wonton_soup -> price -> 0) = '.$soup_price_0.' </br>';
echo '(soup -> wonton_soup -> price -> 1) = '.$soup_price_1.' </br>';
?>