在 Laravel 中将 eloquent 结果转换为关联数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43665430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert eloquent result to associative array in Laravel
提问by Mehdi
How can convert the result from eloquent to associative array. I need to select tow column and have one as key and another as value. Here is the closet I got, however the value is an array. I want it to be only "my_value" column.
如何将结果从 eloquent 转换为关联数组。我需要选择两列并将一个作为键,另一个作为值。这是我得到的壁橱,但值是一个数组。我希望它只是“my_value”列。
$array = Post::select('my_key','my_value')->get()->keyBy('my_key')
回答by Laerte
You should use lists
(Laravel 5.1) or pluck
(Laravel 5.2+):
您应该使用lists
(Laravel 5.1) 或pluck
(Laravel 5.2+):
$array = Post::lists('my_value', 'my_key');
or
或者
$array = Post::pluck('my_value', 'my_key');
回答by Mehdi
I found a way to do so, I'm not sure whether it's proper way to do this performance wise though...
我找到了一种方法,但我不确定这是否是明智地执行此操作的正确方法......
$array = Post::select('my_key','my_value')->get()->mapWithKeys(function ($item) {
return [$item['my_key'] => $item['my_value']];
})->toArray();