通过PHP解析嵌套循环的json

时间:2017-02-20 11:34:47

标签: php mysql json

我正在解析我的json并且我想要使用awnser2 text数组的answer对象更新Option列,但我的输出是text的最后一个{ {1}} 我想要文本对象,你能帮我拿走吗? 这是我的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"}]

这是我的代码:

 <?php
    $con=mysqli_connect("localhost","root","","arrayy");
    // Check connection
    if (mysqli_connect_errno()){
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    $sql="SELECT `survey_answers`,id_s 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);                        
            // awnser2  
             $answer = array(); 
                foreach ($jason_array as $data) {                   
                        foreach($data['answer'] as $ans){                                                       
                        echo $ans['text']."\n" ;                                                             
                        }                                           
                }
                $answers= implode(',',$ans);
                $sql3="update user_survey_start set awnser2='$answers' where id_s=".$row[1];//run update sql
                echo $sql3."<br>";
                mysqli_query($con,$sql3);                                                                           
          }
    }
    mysqli_close($con);
?>

这是我的输出:

update user_survey_start set awnser2='3,HIGH' where id_s=1 

但我想要这个:

update user_survey_start set awnser2='HIGH,LOW,LOW' where id_s=1 

1 个答案:

答案 0 :(得分:3)

$answers = array();
foreach ($jason_array as $data) {
    foreach($data['answer'] as $ans){
        $answers[] =$ans['text'] ;
    }
}
$answers= implode(',',$answers);