我需要一些关于PHP json的帮助。关于这件事我还是新手。我尝试了其他方法,但似乎没有成功。我有这种json格式:
{
"schedule_backup": [
{
"class_time_id_fk": "1",
"student_id_number": "AR0001",
"teacher_id_number": "ACAD-0091",
"class_type_id_fk": "1",
"room_assignment_id_fk": "4",
"books_materials_id_fk": "225",
"class_level_id_fk": "23",
"subject_id_fk": "57"
},
{
"class_time_id_fk": "2",
"student_id_number": "AR0001",
"teacher_id_number": "ACAD-0049",
"class_type_id_fk": "1",
"room_assignment_id_fk": "41",
"books_materials_id_fk": "211",
"class_level_id_fk": "4",
"subject_id_fk": "58"
}
]
}
我想在桌子上展示它们。这是我的代码:
我的观点
echo $jsonString = $this->MClassSchedule->parse_schedule_backup();
$jsonArray = json_decode($jsonString,true);
echo $jsonArray['schedule_backup']['class_time_id_fk'];
模型
function parse_schedule_backup(){
$this->db->select('*');
$this->db->from('class_schedule_backup');
$query = $this->db->get();
foreach ($query->result() as $rows) {
return $rows->data;
}
}
答案 0 :(得分:1)
除非你以异步方式或通过API传递它,否则将它转换为JSON然后返回它似乎很麻烦......只需像下面的模型一样返回数据数组。
<强>模型强>
function parse_schedule_backup(){
$this->db->select('*');
$this->db->from('class_schedule_backup');
$query = $this->db->get();
// Return associative data array
return $query->result_array();
}
然后在视图中,只循环遍历表结构内的行。人们对模板表有不同的风格,但下面有一种方法(显然不包括所有列)。
我的观点
<?php
// You probably want to do this in the controller and pass the data to the view
$data = $this->MClassSchedule->parse_schedule_backup();
// Create table header
?>
<table>
<thead>
<tr>
<th>Class ID</th>
<th>Teacher ID</th>
<th>Student</th>
</tr>
</thead>
<tbody>
<?php
// You probably want to check for a non-empty array and provide an error if needed
foreach($data as $row){
$json = json_decode($row['data'], TRUE);
?>
<tr>
<td><?= $json['schedule_backup']['timeID_1']['class_time_id_fk'] ?></td>
<td><?= $json['schedule_backup']['timeID_1']['student_id_number'] ?></td>
<td><?= $json['schedule_backup']['timeID_1']['teacher_id_number'] ?></td>
</tr>
<?php
}
?>
</tbody>
</table>