将Array转换为JSON字符串php

Ble*_*ien 4 php arrays 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']             
           )
Run Code Online (Sandbox Code Playgroud)

从这里我想让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"}
Run Code Online (Sandbox Code Playgroud)

这是我的代码

$data =json_encode($prebook);
$json='apiBlockTicketRequest:'.$data;
echo $json;
Run Code Online (Sandbox Code Playgroud)

但是当我使用验证JSON字符串时,我将收到以下错误

期待对象或数组,而不是字符串.[代码1,结构1]

错误:字符串应该用双引号括起来.

Rob*_*ert 13

您通过添加apiBlockTicketRequest到输出创建无效的json

 $json='apiBlockTicketRequest'.$data;
Run Code Online (Sandbox Code Playgroud)

相反,你可以做到

$json = json_encode(['apiBlockTicketRequest' => $prebook]);
Run Code Online (Sandbox Code Playgroud)