我是 php json 对象的新手。我正在尝试从我的数据库表数据创建以下 json 格式。Visits基本上是一个对象。但是我的对象知识非常有限,所以我陷入了困境。"visits": { "order_1": { "location": { "name": "6800 Cambie", "lat": 49.227107, "lng": -123.1163085 }, "start": "9:00", "end": "12:00", "duration": 10, "load": 1, "type": "A", "priority": "high" }}但我得到的是 json 格式以下。这是错误的。{ "visits": [ { "order_1": { "location": { "name": "21 Marara Court, ALBANY CREEK QLD 4035", "lat": "-37.7044", "lng": "145.1006" } } }, { "order_2": { "location": { "name": "Unit 7, 19 O'Connell Street, KANGAROO POINT QLD 4169", "lat": "-37.6389", "lng": "145.1950" } } }, ], "fleet": { "vehicle_1": { "start_location": { "id": "depot", "name": "23 Moverly Rd", "lat": -33.9356141, "lng": 151.2425993 }, "end_location": { "id": "depot", "name": "23 Moverly Rd", "lat": -33.9356141, "lng": 151.2425993 } } },}问题出在"visits": [阵列上。但我需要对象。所以我的 php 代码如下:foreach ($orders as $value) { $orders2[] = array( "order_$i"=> array( "location"=> array( "name"=> $value['address'], "lat"=> $value['lat'], "lng"=> $value['long'] ), ), );}$data = array( "visits" => $orders2, "fleet"=> array( "vehicle_1"=> array( "start_location"=> array( "id"=> "depot", "name"=> "23 Moverly Rd", "lat"=> -33.9356141, "lng"=> 151.2425993 ), "end_location"=> array( "id"=> "depot", "name"=> "23 Moverly Rd", "lat"=> -33.9356141, "lng"=> 151.2425993 ), ) ),);如果有人能给我任何想法会更好。谢谢 :)
1 回答
繁花不似锦
TA贡献1851条经验 获得超4个赞
要获取对象,json_encode您必须使用自定义数组键。
尝试这个:
foreach ($orders as $value) {
$orders2["order_$i"] = array(
"location"=> array(
"name"=> $value['address'],
"lat"=> $value['lat'],
"lng"=> $value['long']
),
);
}
只是为了完整性:
也可以使用JSON_FORCE_OBJECT中的选项json_encode或者直接使用aStdClass强制获取json对象。但是在您的情况下,结构无论如何都是错误的,因此上面的代码应该可以正常工作。
- 1 回答
- 0 关注
- 96 浏览
添加回答
举报
0/150
提交
取消