我是 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
),
)
),
);
如果有人能给我任何想法会更好。谢谢 :)
繁花不似锦