条件为json数组通过PHP

时间:2017-02-23 08:34:44

标签: php mysql arrays json

我正在解析这个json数组并且我想要text answer对象并将其放入新列awnser2,这是一行< / strong>我的json行, 在json中回答38和39与text相同但是anser 40是Descriptive Awnser,我得到了非法的字符串偏移&#39; text&#39;对于 Hello Word ,我如何能够在输出中同时拥有它们?

[{"id":"38","answer":[{"option":"3","text":"HIGH"}],"type":"a"},
 {"id":"39","answer":[{"option":"3","text":"LOW"}],"type":"b"},
 {"id":"40","answer":["Hello Word"],"type":"c"}]

这是我的代码:

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

    $json = preg_replace('/\r|\n/','\n',trim($json));   
    $jason_array = json_decode($json,true);
 $answers = array();
            foreach ($jason_array as $data) {
                    if (array_key_exists('answer', $data)) {   
                        foreach($data['answer'] as $ans){
                                $answers[] =$ans['text'] ;
                        }
                    }
            }
            if(!empty($answers)) {
             $answers= implode('',$answers); /// implode yes if you got values
            } 
            else { 
                $answers = 'Nothing Find'; //blank if not have any values
            }
            $sql3="update user_survey_start set awnser2='$answers' where us_id=".$row[1];//run update sql
            echo $sql3."<br>";
            mysqli_query($con,$sql3);
        }
    }
}
mysqli_close($con);
?>

我希望text of Awnser:为......到39而Awnser:为40,40是最后一个

1 个答案:

答案 0 :(得分:1)

检查键是否设置否则指定值

foreach ($jason_array as $data) {
                    if (array_key_exists('answer', $data)) {   
                        foreach($data['answer'] as $ans){
                              $answers[] = isset($ans['text']) ? $ans['text'] : $ans;                                
                        }
                    }
            }