PHP中嵌套的JSON对象和数组

时间:2017-09-08 20:00:44

标签: php arrays json

我尝试使用类似

的结构创建JSON对象
  {
     "events": [
        {
           "eventId": <string>,
           "location": <string>,
           "dates": [<string>, <string>],
           "price": <number>,
           "options": [
              {
                 "name": <string>, 
                 "code": <number>, 
                 "surcharge": <number>
              }, {}, {}...
           ],
        }, {}, {}...
     ]
  }

我的测试PHP代码看起来像

    $event_data[] = array(
        "eventId" => 'A001',
        "location" => 'Pool',
        "dates" => array('2017-10-15T11:45:00Z','2017-10-15T18:00:00Z'),
        "price" => 125,
         "options" => array(
             { 
             "name" => "soda", 
             "code" => 1, 
             "surcharge" => 0
             },  
             { 
              "name" => "beer", 
              "code" => 2, 
              "surcharge" => 25
            }
            )
     );
$data = json_encode(array('evets' => $event_data));

不知怎的,我无法将JSON对象字段options创建为其他JSON数组,以便将其作为

           "options": [
              {
                 "name": <string>, 
                 "code": <number>, 
                 "surcharge": <number>
              },
              {
                 "name": <string>, 
                 "code": <number>, 
                 "surcharge": <number>
              },
              {
                 "name": <string>, 
                 "code": <number>, 
                 "surcharge": <number>
              }
           ],

我知道我在那个地方做错了什么但不知道是什么。

1 个答案:

答案 0 :(得分:1)

您需要转换您的选项数组,如下所示: -

"options" => array(
             array( 
             "name" => "soda", 
             "code" => 1, 
             "surcharge" => 0
             ),  
             array( 
              "name" => "beer", 
              "code" => 2, 
              "surcharge" => 25
            )
        )

输出: - https://eval.in/858403