我有一个关于在php中格式化json的问题。这是我的代码
公共函数测试(){
if (!empty($_POST)) {
$this->db->select('*');
$this->db->from('trash_table');
$this->db->where('Description',$_POST['Descp']);
$q = $this->db->get();
if($q->num_rows() > 0 )
//here should be something better
print json_encode($q->result());
}
使用我当前的简单php代码,我只是将所有内容都作为一个JSONArray。
[
{"ID":1,"Description":"hello",
{"ID":2,"Description":"hellou"}
]
但我想用我自己的方式格式化它,像这样。。。希望你们帮忙。提前感谢!
{
"Answer": {
"Success": "Yup"
},
"列表":[
{"ID":1,
"Description":"hello"},
{"ID":2,
"Description":"hellou"}]
}
$result = array(
'Answer' => array('Sucess'=>'Yup'),
'List' => array(
array('id' => 1, 'Description' => 'hello'),
)
);
print json_encode($result);
将打印:
{"Answer":{"Sucess":"Yup"},"List":[{"id":1,"Description":"hello"}]}
试试这个:
$list = $q->result();
$result = array( "Answer" =>
array ( "success" => "Yup" ),
"List" => $list
);
print json_encode($result);