简体   繁体   English

从MySQL查询格式化JSON PHP

[英]Format JSON PHP from MySQL Query

I have a question about formating a json in php. 我有一个关于在php中格式化json的问题。 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. 使用我当前的简单php代码,我将所有内容作为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"}]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM