如何将json的主节点作为对象数组返回?

如何将json的主节点作为对象数组返回?

问题描述:

I have created this code:

$lists = $this->db->select("SELECT * FROM LOGGER");

    $results = array();
    $results['information'] = array();

    $informations = $this->db->select("SELECT * FROM INFO WHERE code = :ccode", array("ccode" => "3"));

    foreach($informations as $item)
    {
            $results['information'][] = $item;
    }

    $response = array(
        "stack" => $lists,
        "information" => $results['information']
    );

    if(!empty($response['details']))
    {
        return '{"logger": ' . json_encode(array_values($response)) . '}';
    }

I take a stack information from my database and create two arrays. The first save all the informations stack that you can see below; the second array save only the description of the stack. Later I create a result array that save in each index stack and information the result of the two query. Now the final result is this:

{
"logger": {
   "stack": { 
    "Code": "RB01", 
    "Descri": null, 
    "Created": "2016-03-09 04:36:04"
   },
    "information": [
      {
        "Id": "RB01",
        "numeric": 1
      },
      {
        "Id": "RB01",
        "numeric": 2
      },
      {
        "Id": "RB01",
        "numeric": 3
      }
    ]
  }
}

but my goal is create a structure like the following:

{
"logger": [
   {
    "stack": [
      {
        "Code": "RB01",
        "Descri": null,
        "Created": "2016-03-09 04:36:04"
      }
    ],
    "information": [
      {
        "Id": "RB01",
        "numeric": 1
      },
      {
        "Id": "RB01",
        "numeric": 2
      },
      {
        "Id": "RB01",
        "numeric": 3
      }
    ]
  }
]
}

which change I should do in my code?

For me, you should just change:

return '{"logger": ' . json_encode(array_values($response)) . '}';

with :

return '{"logger": ' . json_encode(array($response)) . '}';

It looks like you are just wrapping the object in another array?

if(!empty($response['details']))
{
    $encoded = array(array_values($response));
    return '{"logger": ' . json_encode($encoded) . '}';
}

Also, it is generally safer to create a new array json_encode that than writing your own json.

if(!empty($response['details']))
{
    $encoded = array(array_values($response));
    $result = array(
        'logger' => array(array_values($response)),
    );
    return json_encode($result);
}