php - Codeigniter - Parse each row of json data -
hi using foreach loop parse each row of json data..
what exactly trying json data view , sending controller parsing each row of json insert database.. trying insert data putting in loop , calling setcurrentattendance($item) present in model. if approach wrong please let me know correct one..
the php code :
$data = json_decode($_post["json"]); var_dump($data); foreach($data $item){ $this->codegen_model->setcurrentattendance($item); }
note
$this->codegen_model->setcurrentattendance($item);
redirects model trying pass $item array , inserting database..
function setcurrentattendance($data){ $this->db->insert('table_name', $data); if ($this->db->affected_rows() >= '1') { return true; } return false; }
the json data variable $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"}]"
but getting following error , not able guess why ??
<div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;"> <h4>a php error encountered</h4> <p>severity: warning</p> <p>message: invalid argument supplied foreach()</p> <p>filename: controllers/controller_name.php</p> <p>line number: 245</p> </div>
please let me know wrong.
thanks in advance.
update
json encoded data:
"[{\"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\"}]"
your json string invalid. has \t
, \n
in it, shouldn't. have filter out first:
$json = str_replace(array("\t","\n"), "", $_post["json"]); $data = json_decode($json); var_dump($data); foreach($data $item) { $this->codegen_model->setcurrentattendance($item); }
see: this works.
Comments
Post a Comment