Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Illegal string offset error in PHP

I am sending these objects to server to fetch the record and save it. but it is giving me the below given error

array(3) {
[0]=>
array(1) {
    ["answer"]=>
    string(218) "{"id":"19","question_id":"10","answer_text":"Please note that we also maintain you:",  
"iscorrect":"1",
"created_at":"2014-06-07 07:52:12",  
"updated_at":"2014-06-07 07:52:12"}"
  }
  [1]=>
 array(1) {
   ["answer"]=>
    string(218) "{"id":"20","question_id":"10","answer_text":"Please note that we also maintain the following pages and support forums to help you:",  
"iscorrect":"1",
"created_at":"2014-06-07 07:52:13",  
"updated_at":"2014-06-07 07:52:13"}"
 }
[2]=>
array(1) {
  ["answer"]=>
  string(218) "{"id":"21","question_id":"10",  
  "answer_text":"Please note that we also maintain the following pages and support forums to help you:","iscorrect":"0","created_at":"2014-06-07 07:52:13","updated_at":"2014-06-07 07:52:13"}"
}
}

{"error":{"type":"ErrorException","message":"Illegal string offset     'id'","file":"\/home\/learnomatics\/laravel\/mobillz_mlmalp\/app\/controllers\/QuizController.php","line":379}}

I am trying to get the values like

$answers=Input::get('answers');
var_dump($answers);
foreach ($answers as $answer) {
    if(isset($answer['answer'])){
        quiz_que_ans_id=$answer['answer']['id'];
}
}
like image 490
Sajid Ahmad Avatar asked Aug 11 '26 13:08

Sajid Ahmad


2 Answers

The $answer['answer'] variable is a string comprising JSON encoded data; to access that, you need to decode it first:

$data = json_decode($answer['answer'], true);
$quiz_queue_ans_id = $data['id']; // work with decoded data
like image 195
Ja͢ck Avatar answered Aug 13 '26 04:08

Ja͢ck


Here your answer contains a json string. Decode it before fetching any key. Try this :

foreach ($answers as $answer) {
    if(isset($answer['answer'])){
        $ans = json_decode($answer['answer'],true);
        if(is_array($ans)){
            quiz_que_ans_id=$ans['id']; 
        }
    }
}
like image 26
Nishu Tayal Avatar answered Aug 13 '26 03:08

Nishu Tayal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!