0

您好我正在使用 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\"}]"
4

2 回答 2

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);
}

请参阅:这有效

于 2013-04-05T05:39:04.340 回答
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;
        }
?>
于 2013-04-05T05:41:30.490 回答