【问题标题】:Map two collections into keys and values将两个集合映射为键和值
【发布时间】:2021-03-16 09:28:10
【问题描述】:

我有这样的集合 A...

[
    "Gender",
    "Name",
    "Role",
],

...我有一个来自这样的模型实例的集合 B...

[
       App\Models\Staff {
         id: 11,
         name: "John Doe",
         gender: 'Male',
         2: "role",
         role: App\Models\Role {
           id: 1,
           name: "Director",
         },
       },

       App\Models\Staff {
         id: 22,
         name: "Jane Doe",
         gender: 'Female',
         2: "role",
         role: App\Models\Role {
           id: 2,
           name: "Company Secretary",
         },
       },
     ],

我怎样才能将两者结合起来,使我拥有这样的 Collection C...

[
    [
         "Gender" => 'Male',
         "Name" => 'John Doe',
         "Role" => 'Director',
    ],
    [
         "Gender" => 'Female',
         "Name" => 'Jane Doe',
         "Role" => 'Company Secretary',
    ],
]

到目前为止,我已经尝试了一些事情,包括以此为起点。

return $collectionB->map(function ($b) use ($collectionA) {
    return $collectionA->map(function ($a) use ($b) {
        return [
            $a => $b['gender'],
            $a => $b['name'],
            $a => $b['role']['name'],
        ];
    })->all();
})->all();

【问题讨论】:

    标签: php laravel collections


    【解决方案1】:

    您可以通过单个map() 函数来实现这一点

    $data = [
        [
            'id' => 11,
            'name' => "John Doe",
            'gender' => "Male",
            "role" => [
                "id" => 1,
                "name" => 'Director',
            ]
        ],
        [
            'id' => 22,
            'name' => "John Doe",
            'gender' => "Male",
            "role" => [
                "id" => 2,
                "name" => 'Company Secretary',
            ]
        ]
    ];
    
    $keys = [
        "Gender",
        "Name",
        "Role",
    ];
    
    $data = collect($data)->map(function ($row) use ($keys) {
        return [
            $keys[0] => $row['gender'],
            $keys[1] => $row['name'],
            $keys[2] => $row['role']['name'] ?? '',
        ];
    });
    
    
    return $data;
    

    这个输出是

    [{
            "Gender": "Male",
            "Name": "John Doe",
            "Role": "Director"
        },
        {
            "Gender": "Male",
            "Name": "John Doe",
            "Role": "Company Secretary"
        }
    ]
    

    【讨论】:

    • 如果我硬编码姓名、性别、角色等键,我可以做到这一点。但是这些值是动态的,并且来自数据库中的 JSON 列。我的最终目标是让它尽可能动态,这样我就可以传入一个“字段”键,这样代码就可以遍历每个标题,遍历每个记录并将其映射到相应的标题,而无需知道各个名称每个。
    • @riderofrohan07 为什么需要这个?
    猜你喜欢
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 2016-06-08
    相关资源
    最近更新 更多