转换 Laravel 集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46481576/
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
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:44:23 来源:igfitidea点击:
Transform laravel collection
提问by jsd
I need a certain array format like this:
我需要这样的某种数组格式:
$data = [
1 => ['order' => 3],
2 => ['order' => 2],
3 => ['order' => 1]
];
So when I do:
所以当我这样做时:
$ids = $items->transform(function ($item) {
return [$item->id => ['order' => rand(1,10)]];
})->all();
Gives:
给出:
array:3 [
0 => array:1 [
1 => array:1 [
"order" => 8
]
]
1 => array:1 [
2 => array:1 [
"order" => 3
]
]
2 => array:1 [
3 => array:1 [
"order" => 10
]
]
]
How can I transform the array in a specific way I need above? TIA
如何以上面需要的特定方式转换数组?TIA
回答by Hanlin Wang
you can use mapWithKeys, docs is here: https://laravel.com/docs/5.5/collections#method-mapwithkeys
您可以使用 mapWithKeys,文档在这里:https://laravel.com/docs/5.5/collections#method-mapwithkeys
$keyed = $items->mapWithKeys(function ($item) {
return [$item->id => ['order' => rand(1,10)]];
});
$ids = $keyed->all();