试图在json_decode中获取非对象的属性

时间:2017-11-20 13:35:08

标签: php json

我是 JSON的新手我有一个以

的形式从数据库中检索到的json对象
Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [data] => {"vehicle":[{"year":"2000","make":"Ac","model":"Aceca","acquired_year":"2016","acquired_month":"2","use":"Business","distance_driven_to_work_or_school":"2","distance_driven_manually":"10000"}],"first_name":"ADAS","last_name":"DSADSADA","email":"asddsa@sda.com","phone":"dsasasa","postal_code":"","drivers":[{"name":"ssada","birth_year":"2016","birth_month":"2","birth_day":"2","gender":"female","martial_status":"Single","license_number_provided":"yes","license_number":"asddasdas","license_type":"","training_completed":"","years_been_listed_on_auto_policy_in_north_america":"No Previous Experience","license_suspensions":"","accidents":"Select","convictions":"Select","cancellation_reason":"","cancellation_year":"","cancellation_month":"","cancellation_day":""}],"considering_renters_to_reduce_rate":"yes","install_winter_tires":"no","park_in_private_driveway":"yes","willing_to_install_device":"no","years_insured_with_current_company":"4 Years","how_heard_about_us":"asdaa"}
            [date] => 2017-11-20 18:17:52
            [status] => 0
        )

)

现在,当我尝试使用json_decode将其转换为数组时,我正在尝试获取非对象的属性这里是我的代码

<?php
    echo "<pre>";
    print_r($quotes);  //works fine uptil here
    $data = json_decode($quotes->data,true);//the error line
    echo "<pre>";
    print_r($data);
?>

我尝试了几种方法,但它不起作用我尝试了一些其他解决方案以及最终得到错误任何帮助?

2 个答案:

答案 0 :(得分:7)

这是因为$quotes是一个对象数组。试试$quotes[0]->data,例如:

$data = json_decode($quotes[0]->data,true);
// ------------------------^^^

答案 1 :(得分:2)

您正在接收包含数据库中对象的数组。你几乎就在那里,而不是

$data = json_decode($quotes->data,true);

你应该使用

$data = json_decode($quotes[0]->data,true);