doubo7131 2018-08-29 19:08
浏览 100
已采纳

在Codeigniter中生成JSON查询结果

So i have database table named usermeta and have table structure like this :

-----------------------------------------------------------
| ummeta_id | user_id | meta_key    | meta_value          |
-----------------------------------------------------------
| 1         | 1       | fullname    | John Doe            |
| 2         | 1       | birthplace  | New York            |
| 3         | 1       | birthdate   | 1990/01/01          |
| 4         | 1       | mobile      | 0812-3456-7890      |
| 5         | 1       | email       | john.doe@mail.com   |
| 6         | 2       | fullname    | Jon Wick            |
| 7         | 2       | birthplace  | Washington DC       |
| 8         | 2       | birthdate   | 1985/10/21          |
| 9         | 2       | mobile      | 0890-1234-5678      |
| 10        | 2       | email       | wickjohn@mail.com   |

And i try to generate json data for all data from this database using Codeigniter (v 3.1.9) using Controller and Model.

This is my Model (model name: db_usermeta)

function userslist()
{
   $query = $this->db->select('*')
                     ->from('usermeta')
                     ->get();
   return $query->result();
}

This is my Controller

public function userlist()
{
   header('Content-Type: application/json; charset=utf-8');
   $query = $this->db_usermeta->userslist();
   $json_data = array();
   foreach ($query as $key)
   {
      $json_data[$key->meta_key] = $key->meta_value;
   }
   echo json_encode($json_data);
}

The result when i open using my browser to check the json data using web developer tool is only show last record, in this case only show data from user_id 2, like this:

{
  "fullname":"John Wick",
  "birthplace":"Washinton DC",
  "birthdate":"1985/10/21",
  "mobile":"0890-1234-5678",
  "email":"wickjohn@mail.com"
}

What I want to achieve is to show all json data nested like this:

"data": [
  {
    "fullname":"John Doe",
    "birthplace":"New York",
    "birthdate":"1990/01/01",
    "mobile":"0812-3456-7890",
    "email":"john.doe@mail.com"
  },
  {
    "fullname":"John Wick",
    "birthplace":"Washinton DC",
    "birthdate":"1985/10/21",
    "mobile":"0890-1234-5678",
    "email":"wickjohn@mail.com"
  }
]

How can i achieve this? Did I make a mistake on my controller and model. I really appreciate your help.

  • 写回答

2条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 Python函数嵌套调用与递归
      • ¥20 不会做,找个好心人帮做,有偿,只要答案,不要说废话
      • ¥15 html页面铺满及插入音乐
      • ¥15 T5模型代码问题求助
      • ¥15 JSON文件存入数据库mysql/MongoDB
      • ¥15 C++实现更大的整数类
      • ¥15 Python怎么实现加减乘除乘方和阶乘呀
      • ¥15 centos8-arm64平台编译安装ray分布式计算框架。
      • ¥20 求帮做一个安卓app,用Android Studio制作。需要整个项目文件。
      • ¥15 使用深度学习对于楼梯尺寸进行检测