循环遍历数组中的JSON数组

时间:2016-02-09 09:30:13

标签: php arrays json

以前我使用foreach循环来访问我的JSON对象中的数据,但现在我已经在数组中嵌套了一个数组。这是我的JSON

{
  "name": "Takeaway Kings",
  "menu": [
    {
      "starter": [
        {
          "name": "Samosas",
          "price": 3.5
        },
        {
          "name": "Chaat",
          "price": 1.99
        }
      ]
    },
    {
      "dessert": [
        {
          "name": "Kulfi",
          "price": 2.5
        },
        {
          "name": "Kheer",
          "price": 2.99
        }
      ]
    },
    {
      "main": [
        {
          "name": "Lamb Biryani",
          "price": 4.5
        },
        {
          "name": "Chicken Tikka Masala",
          "price": 5.99
        }
      ]
    }
  ]
}

我试图遍历菜单中的每个数组,然后遍历每个嵌套数组中的内容。

我之前在更改JSONObject布局之前使用它来输出数据。

<?php foreach($restaurant->menu->starter as $starter){
               echo '<h3>'.$starter->name.'</h3><br><p>'.$starter->price.'</p><br>'; 

           } ?>

2 个答案:

答案 0 :(得分:2)

请使用以下代码以使用内部值

Android

答案 1 :(得分:1)

尝试以下代码:

$json = '{
  "name": "Takeaway Kings",
  "menu": [
    {
      "starter": [
        {
          "name": "Samosas",
          "price": 3.5
        },
        {
          "name": "Chaat",
          "price": 1.99
        }
      ]
    },
    {
      "dessert": [
        {
          "name": "Kulfi",
          "price": 2.5
        },
        {
          "name": "Kheer",
          "price": 2.99
        }
      ]
    },
    {
      "main": [
        {
          "name": "Lamb Biryani",
          "price": 4.5
        },
        {
          "name": "Chicken Tikka Masala",
          "price": 5.99
        }
      ]
    }
  ]
}';

echo '<pre>';
$json_arr = json_decode($json, true);
//print_r(call_user_func_array('array_merge',$json_arr['menu']));

echo "name: " . $json_arr['name'];
echo '<br />';
$menu_array = call_user_func_array('array_merge',$json_arr['menu']);
foreach ($menu_array as $name => $arr) {
    echo '<br />';
    echo "Menu name: " . $name;
    foreach($arr as $v){
        echo '<br />';
        echo $v['name'].' : '.$v['price'];
    }
}

<强>输出:

name: Takeaway Kings
Menu name: starter
Samosas: 3.5
Chaat: 1.99
Menu name: dessert
Kulfi: 2.5
Kheer: 2.99
Menu name: main
Lamb Biryani: 4.5
Chicken Tikka Masala: 5.99