我有一个像这样的数组
我想要得到如下的Json字符串:
```
这是我的代码。
$prebook=array(
'sourceCity'=>$_POST['source'],
'destinationCity'=>$_POST['dest'],
'doj'=>$_POST['doj'],
'routeScheduleId'=>$_POST['routeid'],
'boardingPoint'=>array(
'id'=>$id,
'location'=>$location,
'time'=>$time
),
'customerName'=>$_POST['fname'],
'customerLastName'=>$_POST['lname'],
'customerEmail'=>$_POST['email'],
'customerPhone'=>$_POST['mobileno'],
'emergencyPhNumber'=>$_POST['emc-number'],
'customerAddress'=>$_POST['address'],
'blockSeatPaxDetails'=>array(array(
'age'=>$_POST['age'][$key],
'name'=>$value,
'seatNbr'=>$_POST['seat-no'][$key],
'Sex'=>$_POST['gender'.$no],
'fare'=>$_POST['base-fare'][$key],
'totalFareWithTaxes'=>$_POST['amount'][$key],
'ladiesSeat'=>$ladies,
'lastName'=>$_POST['plname'][$key],
'mobile'=>$_POST['mobileno'],
'title'=>'Mr',
'email'=>$_POST['email'],
'idType'=>$_POST['idtype'],
'idNumber'=>$_POST['id-number'],
'nameOnId'=>$value,
'primary'=>true,
'ac'=>$ac,
'sleeper'=>$sleeper
)),
'inventoryType'=>$_POST['invtype']
)
我想要得到如下的Json字符串:
```
从这里我希望获得以下Json字符串
```apiBlockTicketRequest:{"sourceCity":"Hyderabad","destinationCity":"Bangalore","doj":"2016-01-22","routeScheduleId":"6717","boardingPoint":{"id":"2889","location":"Mettuguda,Opp. Mettuguda Church","time":"04:50PM"},"customerName":"jj","customerLastName":"jjj","customerEmail":"shamonsha665@gmail.com","customerPhone":"7779","emergencyPhNumber":"7878","customerAddress":"gjgj","blockSeatPaxDetails":[{"age":"22","name":"hjhj","seatNbr":"G4","Sex":"F","fare":"900","totalFareWithTaxes":"945","ladiesSeat":false,"lastName":"hjhj","mobile":"7779","title":"Mr","email":"shamonsha665@gmail.com","idType":"Aadhar Card","idNumber":"jkjk","nameOnId":"hjhj","primary":true,"ac":false,"sleeper":false}],"inventoryType":"0"}
这是我的代码。
$data =json_encode($prebook);
$json='apiBlockTicketRequest:'.$data;
echo $json;
但是当我使用这个工具验证 JSON 字符串时,会得到以下错误:
期望对象或数组,而不是字符串。[代码 1,结构 1]
错误:字符串应该用双引号括起来。
$json='{apiBlockTicketRequest:'.$data.'}';
这样写可能更好,尽管自己编写 JSON 通常不是一个好主意。最好让json_encode
来完成所有工作。 - Rein