我想从我的查询中生成json数据。但我不能像我预期的那样得到我的json数据。这是我试过的代码。
<?php
$this->db->select('campus.*, class.*');
$this->db->from('campus');
$this->db->join('class', 'campus.id = class.campus_id');
$campus_info = $this->db->get()->result_array();
foreach ($campus_info as $row) {
$var[]['id'] = $row['id'];
$var[]['campus_name'] = $row['campus_name'];
$var[]['class_id'] = $row['class_id'];
$var[]['class_name'] = $row['name'];
}
$json_data = json_encode($var, JSON_PRETTY_PRINT);
echo '<pre>';
echo $json_data;
echo '</pre>';
exit();
我的查询结果是
Array
(
[0] => Array
(
[id] => 4
[campus_name] => Test Campus Name
[institute_name] => Test Institute Name 1
[class_id] => 11
[name] => STD - VIII
[campus_id] => 4
[name_numeric] => 8
[teacher_id] => 6
)
[1] => Array
(
[id] => 4
[campus_name] => Test Campus Name
[institute_name] => Test Institute Name 1
[class_id] => 15
[name] => A' Level
[campus_id] => 4
[name_numeric] => 12
[teacher_id] => 6
)
想让它像json一样
[{
"id": "7",
"campus_name": "Azimpur",
"class_id": "9",
"class_name": "STD - VI"
}
{
"id": "8",
"campus_name": "Azimpur",
"class_id": "10",
"class_name": "STD - VII"
}]
但是得到
[
{
"id": "4"
},
{
"campus_name": "Test Campus Name"
},
{
"class_id": "11"
},
{
"class_name": "STD - VIII"
},
{
"id": "4"
},
{
"campus_name": "Test Campus Name"
},
答案 0 :(得分:2)
这是你的问题:
foreach ($campus_info as $row) {
$var[]['id'] = $row['id'];
$var[]['campus_name'] = $row['campus_name'];
$var[]['class_id'] = $row['class_id'];
$var[]['class_name'] = $row['name'];
}
在这里,您要在$var
变量的最高级别添加4个元素。
你应该只添加一个元素:
foreach ($campus_info as $row) {
$var[] = [
'id' => $row['id'],
'campus_name' => $row['campus_name'],
'class_id' => $row['class_id'],
'class_name' => $row['name']
];
}
如果您只选择所需的列,则可以将其缩小为:
foreach ($campus_info as $row) {
$var[] = $row;
}
如果您的数据库API具有fetchAll
方法,则可能更进一步。