首页 > 解决方案 > 使用嵌套的 JSON 对象循环 JSON 数组

问题描述

如何遍历 json 有效负载对象并将嵌套user_infoaddressjson 对象正确分配给usersuser_infoaddress列?email并且password被正确分配,但是因为user_infojsonaddress对象它不起作用

用户表

email (string), 
password (string), 
user_info (json), 
address (json)

JSON有效负载

{
    email: 'testing@gmail.com',
    password: 'password',
    user_info: {
        first_name: 'testing'
    }
    address: {
        zip_code: 12345
    }
}

控制器

protected function createOrUpdate(Request $request) {
    $user = new User();
    $uCols = [
            'email',
            'password',
            'user_info.first_name',
            'address.zip_code',
        ];

    $input = $request->only($uCols); // input is the json payload above

    foreach($uCols as $column) {
        if(array_key_exists($column, $input) && !empty($input[$column])) 
        {
            $user->$column = $input[$column]; //email and password are correctly assigned 
        }
    }
    $user->save();
}

标签: phplaravel

解决方案


我想到了。我必须更新我的可填充列数组以仅包含列名而不包括属性user_info.first_name

$uCols = [
        'email',
        'password',
        'user_info',
        'address',
    ];

推荐阅读