试图在php数组中获取非对象的属性

时间:2018-05-17 05:44:49

标签: php arrays json

我遇到了将此字符串解码为数组

的问题
$json_array = json_decode($_POST['time_array'],true);

        for ($i = 0; $i < count($json_array); $i++)
        {
            $day = $json_array->day; 
            $start_time = $json_array->start_time;
            $end_time = $json_array->end_time;

            $insert_time="INSERT INTO `nesbaty_working_time` (`provider_id`,
                                              `day`,
                                              `opening_time`, 
                                              `closing_time`, 
                                              `time`, 
                                              `status`) 
                                              VALUES ('".$provider_id."',
                                              '".$day."', 
                                              '".$start_time."',  
                                              '".$end_time."',  
                                              '".$date."',
                                              '".$status."')";
            mysqli_query($con, $insert_time);

        }

错误是从数组

获取数据
 Trying to get property of non-object 

我的数组字符串是

[{"day":"Monday","start_time":"12 : 00 PM","end_time":"12 : 30 PM"},{"day":"Tuesday","start_time":"12 : 00 PM","end_time":"12 : 30 PM"}]

2 个答案:

答案 0 :(得分:3)

如果您想要返回对象类型,请从json_decode中删除true,如

$json_array = json_decode($_POST['time_array']);

并使用index访问返回的数据,如

$day = $json_array[$i]->day; 
$start_time = $json_array[$i]->start_time;
$end_time = $json_array[$i]->end_time;

答案 1 :(得分:2)

您的JSON是一个多维数组。您必须使用index访问它,如下所示

$json_array[$i]['day'];
$json_array[$i]['start_time'];

另请注意

json_decode($_POST['time_array'],true); // returns an associative array 

json_decode($_POST['time_array']); // returns an object

Reference Link