我创建了这段代码:
$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)) . '}';
}
我从数据库中获取堆栈信息并创建两个数组。第一个保存所有信息堆栈,您可以在下面看到;第二个数组只保存堆栈的描述。稍后我创建一个结果数组,在每个索引stack
和information
中保存两个查询的结果。现在最终结果如下:
{
"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
}
]
}
}
但我的目标是创建如下结构:
{
"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
}
]
}
]
}
我应该在代码中做哪些更改?
答案 0 :(得分:1)
对我来说,你应该改变:
return '{"logger": ' . json_encode(array_values($response)) . '}';
with:
return '{"logger": ' . json_encode(array($response)) . '}';
答案 1 :(得分:0)
看起来你只是将对象包装在另一个数组中?
if(!empty($response['details']))
{
$encoded = array(array_values($response));
return '{"logger": ' . json_encode($encoded) . '}';
}
此外,创建一个新的数组json_encode通常比编写自己的json更安全。
if(!empty($response['details']))
{
$encoded = array(array_values($response));
$result = array(
'logger' => array(array_values($response)),
);
return json_encode($result);
}