简体   繁体   中英

Format JSON PHP from MySQL Query

I have a question about formating a json in php. Here is my code

public function testing() {

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());

}

With my current simple php code, I'm just getting everything as a JSONArray.

[

  {"ID":1,"Description":"hello",

  {"ID":2,"Description":"hellou"}

]

But I want to format it on my own way, something like this...Hope you guys help. Thank you in advanced!

{

"Answer": {

    "Success": "Yup"
          },

"List": [

    {"ID":1,    
    "Description":"hello"},

    {"ID":2,    
    "Description":"hellou"}]

}

尝试这个:

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

$result = array(
  'Answer' => array('Sucess'=>'Yup'),
  'List' => array(
     array('id' => 1, 'Description' => 'hello'),
  )
);
print json_encode($result);

Will print:

{"Answer":{"Sucess":"Yup"},"List":[{"id":1,"Description":"hello"}]}

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