通过PHP解析不完整字符串的json

I'm Parsing This json Array and I Want to Take type Object and Put That in New Column type2, and This is one Row of My json Rows,But my Secend Row is Defference and I Get a Notice, How Can I Make a Condition For Type To Skip This Notice? When I Have Not type In my json This is My json in Row 1 and Is ok:

[{"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"}]

And This is My json in Row 2 Without type and I Get Two ,,:

[{"id":"26","answer":[{"option":"3","text":"HIGH"}]},
{"id":"30","answer":[{"option":"3","text":"LOW"}]},
{"id":"31","answer":[{"option":"3","text":"LOW"}]]

And This is My Code:

<?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) {
            $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);
        }
    }
}
mysqli_close($con);
?>

And This Is My Output: Notice: Undefined index: type in C:\wamp64\www\json\json.php on line 20 update user_survey_start set type2=',,' where us_id=256793

查看全部
dongmao4486
dongmao4486
2017/02/22 06:27
  • json
  • php
  • mysql
  • arrays
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复