Sajid Ahmad
Sajid Ahmad

Reputation: 1144

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'];
}
}

Upvotes: 3

Views: 48154

Answers (3)

Bijendra Sahu
Bijendra Sahu

Reputation: 1

Try the following, which passes the photo into the Form::file facade.

{!! Form::file('photo', $user_master->photo, ['class' => 'control-label input-sm', 'type'=>'file', 'accept'=>'image/*']) !!}

Instead of

{!! Form::file('photo', null, ['class' => 'control-label input-sm', 'type'=>'file', 'accept'=>'image/*']) !!}`

Upvotes: 0

Nishu Tayal
Nishu Tayal

Reputation: 20820

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']; 
        }
    }
}

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173522

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

Upvotes: 9

Related Questions