简体   繁体   English

将php对象转换为json

[英]Converting php object to json

I've a php object that I want to convert to the following json format. 我有一个php对象,我想将其转换为以下json格式。

All the data values are object via a php object in the format: 所有data值都是通过php对象提供的,格式为:

Array ( [0] => stdClass Object ( [id] => 2 
                                 [s1] => 1485
                                 [name] => 1485 
                                 [credit] => '' 
                                 [caption] => '' 
                               )
      )

I'm trying to group the credit, caption , etc. under child . 我正在尝试将credit, caption等归入“ child类别。 Also, I'm unable to get the [ after date in the json format. 另外,我无法以json格式获取[之后的date

{
    "mydata":
    {
        "name":Name,
        "type":"default",
        "date": [
        {
                "s1":"1485",
                "name":"1485",
                "child":
                {
                    "credit":"",
                    "caption":""
                }
            }]
   }
}

Currently, my code looks like: 目前,我的代码如下所示:

foreach ($hits as $hit) {
    $data->mydata->date->s1 = $hit->s1;
    $data->mydata->date->name = $hit->name;
    $data->mydata->date->credit = $hit->credit;
    $data->mydata->date->caption = $hit->caption;
}
$a = json_encode($data);

set $date->mydata->date to an array and you will get the [] $date->mydata->date设置为数组,您将获得[]

And why not making more nested structures? 为什么不制作更多的嵌套结构呢?

The JSON format you're looking at shows that date is an array (the brackets are array notation in javascript), so: 您正在查看的JSON格式显示date是一个数组(方括号是javascript中的数组表示法),因此:

<?php

$var = array(
    'mydata' => array(
        'name' => 'Name',
        'type' => 'default',
        'date' => array(
            array(
                's1' => 1485,
                'name' => '1485',
                'child' => array(
                    'credit' => '',
                    'caption' => '',
                ),
            ),
        ),
    ),
);

print json_encode($var);

prints out: 打印出:

{
    "mydata": {
        "name": "Name",
        "type": "default",
        "date": [
            {
                "s1": 1485,
                "name": "1485",
                "child": {
                    "credit": "",
                    "caption": ""
                }
            }
        ]
    }
}

No need to try and add stdClass instances or anything like that in PHP. 无需尝试添加stdClass实例或PHP中的类似内容。 Just build out a nice clean array and JSON encode will convert to object properties and arrays where necessary. 只需构建一个干净的数组,JSON编码将在必要时转换为对象属性和数组。

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

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