简体   繁体   中英

Converting php object to json

I've a php object that I want to convert to the following json format.

All the data values are object via a php object in the format:

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

I'm trying to group the credit, caption , etc. under child . Also, I'm unable to get the [ after date in the json format.

{
    "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 []

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:

<?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. Just build out a nice clean array and JSON encode will convert to object properties and arrays where necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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