【发布时间】:2025-12-30 11:15:17
【问题描述】:
您好,我正在使用 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\"}]"
【问题讨论】:
-
你在 '$_POST["json"]' 中得到什么数据?是json编码的数据吗??
-
@Mahendra : 我已经更新了.. 看看我的编辑
-
嘿,我已将其发布在答案上,但将其删除,因为我实际上并没有看到它有什么帮助,但值得一试 - 尝试将 json_encode 更改为具有第二个参数: $data = json_decode($_POST['json'], true);这将迫使它成为一个数组而不是一个 php 对象
-
检查您正在使用的双引号。这可能是造成这种情况的原因。试试这个。第0行=>'[{“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"}]'
-
@francisco.preller :我试过 json_decode($_POST['json'], true);但它再次显示相同的错误
标签: php json codeigniter parsing