简体   繁体   English

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

[英]Encoding data into JSON object in php

I have to send the JSON in the following format: 我必须以以下格式发送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"
    }
  }
}

I am using the following code to encode it into JSON and since docls is an array, I am using a loop to put two values into it. 我正在使用以下代码将其编码为JSON,并且由于docls是一个数组,因此我正在使用循环将两个值放入其中。

$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);

When I print the JSON, it becomes: 当我打印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,
    }
   ],
 }

The "docls" should be inside "suomottoRegVO" but is not. “文档”应该在“ suomottoRegVO”内部,但不是。 Please anyone guide me to solve this. 请任何人指导我解决这个问题。

Try this... You need to paas your array under $json_string['suomottoRegVO'] so try this way... 试试这个...您需要在$json_string['suomottoRegVO']$json_string['suomottoRegVO']数组,所以请尝试这种方式...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM