0

I'm Parsing This json Array and I Want to Take text Object of answer and Put That in New Column awnser2, and This is one Row of My json Rows, answer 38 and 39 in json Are Same as text But anser 40 Is Descriptive Awnser, I Got Illegal string offset 'text' for Hello Word, How Can I Make a Condition to Have Both of Them in Output?

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

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

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

I Want to Have text of Awnser: for ....to 39 and Awnser: for 40 , 40 is last awnser

2
  • Your Hello World is not in JSONArray like the previous two. Commented Feb 23, 2017 at 8:36
  • I Know I Want text of Awnser: for 38 and 39 and Awnser: for 40 , 40 is last awnser Commented Feb 23, 2017 at 8:39

1 Answer 1

1

check key is set or not otherwise assign value

foreach ($jason_array as $data) {
                    if (array_key_exists('answer', $data)) {   
                        foreach($data['answer'] as $ans){
                              $answers[] = isset($ans['text']) ? $ans['text'] : $ans;                                
                        }
                    }
            }
Sign up to request clarification or add additional context in comments.

1 Comment

Solved,Greaaaaaaaaaat, You Are Very Intelligent,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.