我解析此JSON数组和我想利用type对象,并提出,在新列type2,这是一个排的我JSON行,我获取的foreach(提供)由于新线的JSON无效参数在某些行。我该如何解决?
这不是奥奇
[{"id":"26","answer":[{"option":"4","text":"Hello
"}],"type":"3"}]
Run Code Online (Sandbox Code Playgroud)
这个是奥基
[{"id":"26","answer":[{"option":"4","text":"Hello"}],"type":"3"}]
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
<?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];
if(!is_null($json)){
$jason_array = json_decode($json,true);
// type2
$type = array();
foreach ($jason_array as $data) {
if (array_key_exists('type', $data)) {
// Now we will only use it if it actually exists
$type[] = $data['type'];
}
}
// lets check first your $types variable has value or not?
if(!empty($type)) {
$types= implode(',',$type); /// implode yes if you got values
}
else {
$types = ''; //blank if not have any values
}
$sql2="update user_survey_start set type2='$types' where us_id=".$row[1];//run update sql
echo $sql2."<br>";
mysqli_query($con,$sql2);
}
}
}
mysqli_close($con);
?>
Run Code Online (Sandbox Code Playgroud)
在json解码之前,用\ n替换新行:
$json = preg_replace('/\r|\n/','\n',trim($json));
$jason_array = json_decode($json,true);
Run Code Online (Sandbox Code Playgroud)