doushan2224 2017-02-22 08:30
浏览 60
已采纳

通过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, Why I Get This Warning for Some Rows? 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"}]

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

That is Strang, Why Some Row Has Output And Some Rows Hasn't Any Output, Those Json Type Are Same. I Find The Problem, Because Some json entered, I Mean. This One Has Warning: Invalid argument supplied for foreach()

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

And This One is Okey

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

How Can I Fix The Problem?

  • 写回答

1条回答 默认 最新

  • donglong2856 2017-02-22 08:53
    关注

    you also try is_array before your for each loop

    if (is_array($jason_array))
    {
         foreach ($jason_array as $data) {
        {
            ...
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。