如何在PHP中正确映射此类数据?

问题描述 投票:2回答:1

我有id的字符串:"1,2,3,4".我需要得到数组:

1 => Post::whereId(1)->get()->created_at
2 => Post::whereId(2)->get()->created_at
3 => Post::whereId(3)->get()->created_at
4 => Post::whereId(4)->get()->created_at

我试试这个:

$postMap = collect($item->posts_id)->mapWithKeys(function ($item) {
            return [
                $item->posts_id => Post::whereId($item->postss_id)->first()->crated_at,
            ];
        });
php laravel
1个回答
1
投票

只需像这样使用pluck()方法:

$array = Post::whereIn('id', explode(',', $arrayString))->pluck('created_at', 'id');
© www.soinside.com 2019 - 2024. All rights reserved.