【问题标题】:Format JSON PHP from MySQL Query从 MySQL 查询格式化 JSON PHP
【发布时间】:2014-08-31 11:48:33
【问题描述】:

我有一个关于在 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"}]

}

【问题讨论】:

    标签: php json post get


    【解决方案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"}]}
    

    【讨论】:

      【解决方案2】:

      试试这个:

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

      【讨论】:

        猜你喜欢
        • 2015-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-30
        • 2011-09-05
        • 1970-01-01
        • 2016-12-31
        相关资源
        最近更新 更多