我需要一个像这样的数组格式:
$data = [
1 => ['order' => 3],
2 => ['order' => 2],
3 => ['order' => 1]
];
所以当我这样做时:
$ids = $items->transform(function ($item) {
return [$item->id => ['order' => rand(1,10)]];
})->all();
给出:
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
]
]
]
如何以上面需要的特定方式转换数组? TIA
答案 0 :(得分:3)
你可以使用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();