在php中将数据编码为JSON对象


Encoding data into JSON object in php

我必须以以下格式发送JSON:

{    
"suomottoRegVO" : {
    "rgdtls" : {
        "aplty" : APLSM
         },
    "docls" : [
     {
         "id" : 123,
         "ty" : 101,
     },
     {
         "id" : 123,
         "ty" : 101,
     }
     ],
"todtls":{ 
   "tonm":"Gaurav Kumar",
   "todg":"Tax Official",
   "pl":"Bangalore",
   "dt":" 12-04-2015 23:05:23"
    }
  }
}

我使用以下代码将其编码为JSON,并且由于docs是一个数组,因此我使用循环将两个值放入其中。

$json_string = array(
                    'suomottoRegVO' => array (
                        'rgdtls'=> array(
                            'aplty'=>'APLSM',
                        ),
                    'todtls' => array(
                        'tonm' => 'Gaurav Kumar',
                        'todg' => 'Tax Official',
                        'pl' => 'Bangalore',
                        'dt' => ' 12-04-2015 23:05:23',
                        )
                       )
                     );
        for ($i=0; $i<2; $i++) { 
                    $docls[] =  array (
                        'id' => '123',
                        'ty' => '101'
                        );
                    }
        $json_string['docls']=$docls;
        json_encode($json_string);
当我打印JSON时,它变成:
{     
"suomottoRegVO" : {
    "rgdtls" : {
        "aplty" : APLSM
     },
    "todtls":{ 
    "tonm":"Gaurav Kumar",
    "todg":"Tax Official",
    "pl":"Bangalore",
    "dt":" 12-04-2015 23:05:23"
    }
}
"docls" : [
    {
    "id" : 123,
    "ty" : 101,
    },
    {
    "id" : 123,
    "ty" : 101,
    }
   ],
 }

" docs "应该在"suomottoRegVO"里面,但是没有。请任何人指导我解决这个问题。

试试这个…你需要在$json_string['suomottoRegVO']下设置你的数组,所以试试这样…

$json_string['suomottoRegVO']['docls']=$docls;
 json_encode($json_string);