Home > Software design >  Getting value of an item in json [duplicate]
Getting value of an item in json [duplicate]

Time:10-07

I want to get value of option key from an json, eg: the array below should return 12 I have tried the following code but I always get 'Undefined array key 0'

    {{ $question->options[0]['option'] }}

the data is stored in a json column of mysql database, the laravel model is Question and column is options I can get the column but i am not able to get the value of option key after getting the data in the column, i don't want to use php foreach

{
    "1": {
        "option": "12",
        "correct": "1"
    }
}


Array ( [1] => Array ( [option] => 12 [correct] => 1 ) ) 1

CodePudding user response:

I got, I was able to do it this way after thorough trial

array_values($question->options)[0]['option']

CodePudding user response:

first you must parse data with json_decode

$question ='{
            "1": {
                "option": "12",
                "correct": "1"
            }
        }';
        $toArray = json_decode($question);
        print_r($toArray->{1}->option); // Accessing invalid object properties
    }
  • Related