2014-08-31 45 views
0

我有一個關於在php中格式化json的問題。這裏是我的代碼從MySQL查詢格式JSON PHP

公共功能測試(){

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"}] 

}

回答

1
$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"}]} 
+0

工作好的:)謝謝你這麼多! – 2014-11-11 00:25:56

1

試試這個:

$list = $q->result(); $result = array("Answer" => array ("success" => "Yup"), "List" => $list ); print json_encode($result);