php - PHP. Map two arrays using the attribute of one against the key of the second
问题描述
I have two arrays:
The first one looks like this:
Array: 8 [▼
0 => array:17 [▼
"id" => 4
"firstname" => "Maria"
"lastname" => "von Moszczenski"
"slug" => "marianne-von-moszczenski"
"email" => "marianne.von.moszczenski@gmail.com"
"email_verified_at" => null
"created_at" => "2019-11-21 17:34:53"
"updated_at" => "2019-11-21 17:34:53"
"deleted_at" => null
]
1 => User {...}
2 => User {...}
3 => User {...}
... unknown number of elements
]
The second array looks like this:
array:8 [▼
"Maria" => 17
"Stefanie" => 2
"Angela" => 3
"Andrea" => 4
"Michelle" => 5
"Yvonne" => 6
"Martina" => 7
"Karolina" => 8
... unknown number of elements...
]
I want to merge both of them so, i get the following structure:
Array: 8 [▼
0 => array:17 [▼
"id" => 4
"firstname" => "Maria"
"lastname" => "von Moszczenski"
"slug" => "marianne-von-moszczenski"
"email" => "marianne.von.moszczenski@gmail.com"
"email_verified_at" => null
"created_at" => "2019-11-21 17:34:53"
"updated_at" => "2019-11-21 17:34:53"
"deleted_at" => null
"total" => 17 // <------ this is the new field
... unknown number of elements...
]
1 => User {...}
2 => User {...}
3 => User {...}
]
So i did this:
foreach ($totalsPerEmployee as $key => $total) {
foreach ($users as $user) {
if ($user['firstname'] === $key) {
$user['totalappointments'] = $total; // if I stop and echo hier I see the new field
}
}
}
If I echo the result of the foreach in the middle, I see that the new field is added, but once the two foreach end, the new field was not added.
My questions is:
This method looks to error prone or if the arrays get too big could lead to performance issues.
Is there any other way to map/combine/intersect or whatever these two arrays mapping one attribute (firstname) in the first one against the key of the second one?
if there is not any "magic" method and I have to make the two loops. What am I doing wrong?
解决方案
您可以转动循环,您已经有了由用户名索引的总计数组,所以只需循环用户数组,如果它有一个值,然后将其添加...
foreach ($users as &$user) {
if (isset($totalsPerEmployee[$user['firstname']])) {
$user['totalappointments'] = $totalsPerEmployee[$user['firstname']];
}
}
unset($user);
还要确保您更新原始数组,使用&$user
对数据的引用,否则您(如您所见)更新数据的副本。只是为了确保 -unset($user)
在循环之后使用以防万一。
推荐阅读
- javascript - 然后 Vs Await 问题
- php - .htaccess 停止目录列表并转发到 handler.php
- python-3.x - 从文件python中检索列表类型的多个字典
- rust - 为什么我不能在一行中调用两次 FnMut?
- r - 为什么运算符 %in% 不能与小标题一起使用?
- python - 为什么打印不显示整行?
- google-cloud-platform - 谷歌云运行无法触发构建:权限'cloudbuild.builds.create'被拒绝
- go - Cannot build go_proto_library with gRPC
- python-3.x - 如何从收集子任务中获取异步父任务?
- r - R - 自动化多图输入 ggPlot2