首页 > 解决方案 > Laravel 集合图的方法来展平多维

问题描述

我有这段代码,我想将集合重命名为不同的键和值。但是当我使用map方法时,值返回到它们现有的值key,我想删除使用 map 展平多维集合的键method

检索模型:

$user = User::find(123)->orderByDesc('created_at')->get()->pluck('name', 'id');

$data = $user->map(function ($value, $key) {
    return [
        'id'   => $key,
        'text' => $value,
    ];
});

预期结果:

$data = [
    [
        'id' => 3,
        'text' => 'Shinka Nibutani',
    ], [
        'id' => 2,
        'text' => 'Kashiwagi Rein',
    ], [
        'id' => 1,
        'text' => 'Alice Zuberg',
    ],
]

实际结果:

$data = [
    3 => [
        'id' => 3,
        'text' => 'Shinka Nibutani',
    ],

    2 => [
        'id' => 2,
        'text' => 'Kashiwagi Rein',
    ],

    3 => [
        'id' => 1,
        'text' => 'Alice Zuberg',
    ],
]

标签: arrayslaraveldictionarycollections

解决方案


你只需要在最后添加 values() 。像这样的东西:

$data = $user->map(function ($value, $key) {
    return [
        'id'   => $key,
        'text' => $value,
    ];
})->values();

Laravel 文档:https ://laravel.com/docs/7.x/collections#method-values

值()

values 方法返回一个新集合,其中键重置为连续整数:

$collection = collect([
    10 => ['product' => 'Desk', 'price' => 200],
    11 => ['product' => 'Desk', 'price' => 200]
]);

$values = $collection->values();

$values->all();

/*
    [
        0 => ['product' => 'Desk', 'price' => 200],
        1 => ['product' => 'Desk', 'price' => 200],
    ]
*/

推荐阅读