【发布时间】:2017-02-21 06:34:35
【问题描述】:
我正在解析我的 json 并将其放入 3 个新列,id2、awnser2 和type2,但是有些行是 NULL,我怎样才能创建一个条件来用 Null 更新那些行?(使id2,type2,awnser2 = 某些行为空),
这是我的 json 的一行:
[{"id":"26","answer":[{"option":"3","text":"HIGH"}],"type":"3"},
{"id":"30","answer":[{"option":"3","text":"LOW"}],"type":"3"},
{"id":"31","answer":[{"option":"3","text":"LOW"}],"type":"3"}]
我的意思是,例如:我的第二行是 NULL 并且不是 Json,并且我的输出中有错误, 这是我的代码:
<?php
$con=mysqli_connect("localhost","root","","array");
mysqli_set_charset($con,"utf8");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT `survey_answers`,us_id FROM `user_survey_start`";
if ($result=mysqli_query($con,$sql)){
while ($row = mysqli_fetch_row($result)){
$json = $row[0];
$jason_array = json_decode($json,true);
// id2
$id = array();
foreach ($jason_array as $data) {
$id[] = $data['id'];
}
$ids= implode(',',$id);
$sql1="update user_survey_start set id2='$ids' where us_id=".$row[1];//run update sql
echo $sql1."<br>";
mysqli_query($con,$sql1);
// type2
$type = array();
foreach ($jason_array as $data) {
$type[] = $data['type'];
}
$types= implode(',',$type);
$sql2="update user_survey_start set type2='$types' where us_id=".$row[1];//run update sql
echo $sql2."<br>";
mysqli_query($con,$sql2);
// awnser2
$answers = array();
foreach ($jason_array as $data) {
foreach($data['answer'] as $ans){
$answers[] =$ans['text'] ;
}
}
$answers= implode(',',$answers);
$sql3="update user_survey_start set awnser2='$answers' where us_id=".$row[1];//run update sql
echo $sql3."<br>";
mysqli_query($con,$sql3);
}
}
mysqli_close($con);
?>
【问题讨论】:
-
问题不清楚请尽量简单解释
-
我更新了我的问题,我可以看到输出正确,但是对于 NULL 行我有这个错误:
Warning: Invalid argument supplied for foreach() in C:\wamp64\www\json\json.php on line 16 -
先
var_dump($jason_array)看看你得到了什么 -
我是 PHP 新手,不太懂,该怎么办?
-
正如您在第 16 行中显示的错误 Invalid argument for foreach 意味着
$jason_array不是数组,但您的var_dump($jason_array)显示的是数组。再尝试一件事echo is_array($jason_array)