通过PHP解析数组和对象json - 提供的参数无效

时间:2017-02-22 08:30:36

标签: php mysql arrays json

我正在解析这个json数组,我想把type对象放在新列type2中,这是我的json的一行行, 为什么我会针对某些行发出此警告? Warning: Invalid argument supplied for foreach() in C:\wamp64\www\json\json.php on line 18

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

这是我的代码:

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

那是Strang,为什么有些行输出而有些行没有任何输出,那些Json类型是相同的。 我发现问题,因为有些json进入,我的意思是。 这个人有Warning: Invalid argument supplied for foreach()

[{"id":"26","answer":[{"option":"4","text":"Hello
"}],"type":"3"}]

这一个是Okey

[{"id":"26","answer":[{"option":"4","text":"Hello"}],"type":"3"}]

如何解决问题?

1 个答案:

答案 0 :(得分:1)

你也可以在每个循环之前尝试is_array

if (is_array($jason_array))
{
     foreach ($jason_array as $data) {
    {
        ...
    }
}