合并数组内的对象

时间:2019-10-05 07:46:40

标签: arrays laravel eloquent

我的代码在这里返回这样的响应

{
    "code": 422,
    "message": "The given data was invalid.",
    "errors": {
        "0": {
            "first_name": [
                "The first name field is required."
            ]
        },
        "1": {
            "last_name": [
                "The last name field is required."
            ]
        },
        "2": {
            "mobile": [
                "The mobile must be an integer.",
                "The mobile must be at least 9."
            ]
        }
    }
}

我需要合并对象并删除数字以这样返回

{
    "code": 422,
    "message": "The given data was invalid.",
    "errors": {

            "first_name": [
                "The first name field is required."
            ],

            "last_name": [
                "The last name field is required."
            ],

            "mobile": [
                "The mobile must be an integer.",
                "The mobile must be at least 9."
            ]

    }
}

private function transformErrors(ValidationException $exception)
{
    $errors = [];

    foreach ($exception->errors() as $field => $message) {
         $errors[]  =  [
              $field  => $message
          ];

    }
    return  (object)$errors;
}

以这种方式处理响应的最佳方法是什么

2 个答案:

答案 0 :(得分:0)

您可以使用array_values()函数从错误数组中收集值。像这样:

$yourArray['errors'] = array_values($yourArray['errors']);

答案 1 :(得分:0)

如果我理解正确,您只想将多维数组转换为简单数组。

您可以尝试使用:

A