我必须根据公共密钥向集合添加列...
$usersDatas = $users->each(function ($record) use ($timeData) {
$times = array_first($timeData, function ($value, $key) use ($record) {
return $value['id'] === $record['id'];
});
$record['totalTime'] = $times['totalTime'];
$record['spendTime'] = $times['spendTime'];
$record['remainingTime'] = $times['remainingTime'];
var_dump($record);
});
dd($usersDatas);
里面的dd($ records)给了我正确的结果......但我无法在外面提取结果......
dd($ records)给了我:
array:17 [▼
"id" => 1
"ua_id" => 351
"grade_id" => 584
"metier_id" => 18
"nom" => "XXX"
"prenom" => "XXX"
"matricule" => "XXX"
"email" => null
"datenaissance" => "XXX"
"casque" => null
"created_at" => "2018-01-30 09:59:32"
"updated_at" => "2018-01-30 09:59:32"
"deleted_at" => null
"totalTime" => 240
"spendTime" => 0
"remainingTime" => 0
]
虽然dd($ usersDatas)给了我这个:
0 => array:14 [▼
"id" => 1
"ua_id" => 351
"grade_id" => 584
"metier_id" => 18
"nom" => "XXX"
"prenom" => "XXX"
"matricule" => "XXX"
"email" => null
"datenaissance" => "XXX"
"casque" => null
"created_at" => "2018-01-30 09:59:32"
"updated_at" => "2018-01-30 09:59:32"
"deleted_at" => null
"pivot" => array:5 [▶]
最后3个字段丢失......
"totalTime" => 240
"spendTime" => 0
"remainingTime" => 0
答案 0 :(得分:1)
您必须使用$collection->map(function($item) { ... })
:
// we will simply override $users here with an updated collection
$users = $users->map(function ($record) use ($timeData) {
$times = array_first($timeData, function ($value, $key) use ($record) {
return $value['id'] === $record['id'];
});
$record['totalTime'] = $times['totalTime'];
$record['spendTime'] = $times['spendTime'];
$record['remainingTime'] = $times['remainingTime'];
var_dump($record);
return $record;
});
dd($users);
$collection->each(function($item) { ... })
确实正在为每个项执行函数,但不修改集合。此方法可用作foreach ($collection as $item) { ... }
的替代,例如当回调函数function($item) { ... }
被定义在代码中的其他地方时。