在代码点火器中生成 JSON 查询结果



所以我有一个名为usermeta的数据库表,并且表结构如下:

-----------------------------------------------------------
| 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   |

我尝试使用控制器和模型使用 Codeigniter (v 3.1.9( 为来自此数据库的所有数据生成 json 数据。

这是我的模型(模型名称:db_usermeta(

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

这是我的控制器

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

当我使用浏览器打开使用 Web 开发人员工具检查 json 数据时,结果仅显示最后一条记录,在这种情况下仅显示 user_id 2 中的数据,如下所示:

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

我想要实现的是显示嵌套的所有 json 数据,如下所示:

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

我怎样才能做到这一点?我的控制器和模型有误吗?我非常感谢您的帮助。

您的$key->meta_key将覆盖每条记录。 这就是为什么只出现最后一条记录的原因。实际上,您不需要遍历即可获取 json 数据。

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

只需将您的控制器代码更改为此代码,这将返回 JSON 数据。

由于两条记录的元键fullname相同,因此您需要将键名称更改为唯一的名称

foreach ($query as $key)
{
$json_data[$key->meta_key] = $key->meta_value;
}

$json_data[$key->meta_key]更改为$json_data[$key->meta_key.$key->user_id]或者干脆将其更改为$json_data[$key->ummeta_id]

最新更新