您好我正在使用foreach循环来解析每行json数据..
完全我正在尝试从视图中获取json数据,然后将其发送到控制器,我将解析json的每一行以将其插入到我的数据库中..我正在尝试通过将数据放入循环并调用模型中存在的setCurrentAttendance($ item)来插入数据。如果我的方法有误,请让我知道正确的方法..
php代码是:
$data = json_decode($_POST["json"]);
var_dump($data);
foreach($data as $item){
$this->codegen_model->setCurrentAttendance($item);
}
注意
$this->codegen_model->setCurrentAttendance($item);
重定向到我的模型,我试图将$ item作为数组传递并将其插入数据库..
function setCurrentAttendance($data){
$this->db->insert('table_name', $data);
if ($this->db->affected_rows() >= '1')
{
return TRUE;
}
return FALSE;
}
json数据变量$ data是:
"[{"roll_no":"1101","full_name":"John Smith","dayspresent":"1","totalclasses":"2","percent_att":"50","hasAttended":"P","att_date":"Thu Apr 04 2013","st_class":"1","st_section":"A"},
{"roll_no":"1102","full_name":"Ram Puri","dayspresent":"4","totalclasses":"4","percent_att":"100","hasAttended":"P","att_date":"Thu Apr 04 2013 ","st_class":"1","st_section":"A"}]"
但我收到以下错误而无法猜出为什么?
<div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">
<h4>A PHP Error was encountered</h4>
<p>Severity: Warning</p>
<p>Message: Invalid argument supplied for foreach()</p>
<p>Filename: controllers/controller_name.php</p>
<p>Line Number: 245</p>
</div>
请告诉我错误的地方。
提前致谢。
更新
json编码数据:
"[{\"roll_no\":\"1101\",\"full_name\":\"John Smith\",\"dayspresent\":\"1\",\"totalclasses\":\"2\",\"percent_att\":\"\n\t\t\t50\t\t\t\",\"hasAttended\":\"P\",\"att_date\":\"Fri Apr 05 2013 \",\"st_class\":\"1\",\"st_section\":\"A\"},{\"roll_no\":\"1102\",\"full_name\":\"Ram Puri\",\"dayspresent\":\"4\",\"totalclasses\":\"4\",\"percent_att\":\"\n\t\t\t100\t\t\t\",\"hasAttended\":\"A\",\"att_date\":\"Fri Apr 05 2013 \",\"st_class\":\"1\",\"st_section\":\"A\"}]"
答案 0 :(得分:3)
您的JSON字符串无效。它中包含\t
和\n
,但它不应该。你必须先过滤掉那些:
$json = str_replace(array("\t","\n"), "", $_POST["json"]);
$data = json_decode($json);
var_dump($data);
foreach($data as $item)
{
$this->codegen_model->setCurrentAttendance($item);
}
请参阅:this works。
答案 1 :(得分:0)
请使用此代码。它可能适合你。
修改强>
代码更新以打印每个学生的全名作为示例。
<?php
$data = '{"students" : [{"roll_no":"1101","full_name":"John Smith","dayspresent":"1","totalclasses":"2","percent_att":"50","hasAttended":"P","att_date":"Fri Apr 05 2013 ","st_class":"1","st_section":"A"},{"roll_no":"1102","full_name":"Ram Puri","dayspresent":"4","totalclasses":"4","percent_att":"100","hasAttended":"A","att_date":"Fri Apr 05 2013 ","st_class":"1","st_section":"A"}]}';
$data = json_decode($data);
//var_dump($data);
foreach($data->students as $item){
print $item->full_name;
}
?>