【问题标题】:How to convert array with objects to one object like Laravel Request object如何将带有对象的数组转换为一个对象,例如 Laravel Request 对象
【发布时间】:2020-06-07 02:53:34
【问题描述】:

我有一个这样的数组:

[{FirstName: "fff"},
{LastName: null},
{Nationality: null},
{Year: null},
{Month: null},
{Day: null}]

我需要将它转换成这样的一个对象:(使用 Laravel 或使用 JS)

{FirstName: "fff",
LastName: null,
Nationality: null,
Year: null,
Month: null,
Day: null}

我需要一个与 Laravel 请求对象完全一样的对象。我该怎么做?

【问题讨论】:

    标签: arrays laravel object laravel-5


    【解决方案1】:

    假设数组嵌套对象是变量$a

    function multipleObjsToObj($a) {
        $b = json_encode($a, true);     // encode to string
        $array = json_decode($b, true); // decode to all array
    
        // use collection flatMap or mapWithKeys to flatten with keys:
        // $flatten_array = collect($array)->mapWithKeys(function($item){return $item;})->toArray();
        $flatten_array = collect($array)->flatMap(function($item){return $item;})->all();
    
        return (object) $flatten_array; // here become to object.
    }
    

    【讨论】:

      猜你喜欢
      • 2023-02-15
      • 1970-01-01
      • 2019-09-18
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      相关资源
      最近更新 更多