合并两个(或更多)数组并保留最高的值?
我有一个基于权限/组的设置,我正在尝试合并结果。例如,一个用户可能与四个组相关联:
| username | passwd | email | groups |
| test_user | 9agb9 | [email protected] | g1, g2, g3, g4 |
分组表:
| group | perm1 | perm2 | perm3 | perm4 | perm5 | perm5 | perm7 |
| g1 | 1 | 0 | 0 | 0 | 1 | 0 | 2 |
| g2 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
| g3 | 0 | 1 | 0 | 0 | 2 | 0 | 0 |
| g4 | 0 | 0 | 0 | 0 | 1 | 1 | 0 |
我希望获取这四行的结果(从数据库查询存储为数组)并将它们合并到一个数组,如下所示:
| group | perm1 | perm2 | perm3 | perm4 | perm5 | perm5 | perm7 |
| combined | 1 | 1 | 0 | 1 | 2 | 1 | 2 |
每个数组中的最高值成为组合数组中的值。如果 100 条记录中有 1 条是“2”,其余的是“1”或“0”,那么我需要在结果中包含“2”。
我查看了 array_merge,但它根据指定给函数的变量的顺序保留值。
I've got a permissions/group based setup that I'm trying to merge results on. For example, a user might be associated with four groups:
| username | passwd | email | groups |
| test_user | 9agb9 | [email protected] | g1, g2, g3, g4 |
grouping table:
| group | perm1 | perm2 | perm3 | perm4 | perm5 | perm5 | perm7 |
| g1 | 1 | 0 | 0 | 0 | 1 | 0 | 2 |
| g2 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
| g3 | 0 | 1 | 0 | 0 | 2 | 0 | 0 |
| g4 | 0 | 0 | 0 | 0 | 1 | 1 | 0 |
I'm looking to take the results of those four rows (stored as an array from a DB query) and merge them down to one array, which would look like this:
| group | perm1 | perm2 | perm3 | perm4 | perm5 | perm5 | perm7 |
| combined | 1 | 1 | 0 | 1 | 2 | 1 | 2 |
The highest value from each array becomes the value in the combined array. If 1 out of 100 records is "2" and the rest are "1" or "0" then I'd need "2" to be in the result.
I've looked at array_merge, but it keeps the value depending on the order of variables specified to the function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许您希望数据库已经处理这个问题:
Maybe you want this handled already by the DB:
您需要创建一个新的主数组,然后循环遍历子数组,并且仅在
child['value'] > 时更新主数组。主控['值']
You'll need to make a new master array, then loop through your child arrays and only update the master when
child['value'] > master['value']
最近不得不在 PHP 中做类似的事情:
当然,这可以写得更简单一些,并且您可以使用三元运算符来缩短它,但是这个详细的显示显示了如何更语义地做到这一点。这是相对较快的,我用它来帮助一次合并数百个帐户设置,没有任何问题。
Had to do something similar recently in PHP:
Of course, this can be written a little more simply, and you could use a ternary operator to shorten it, but this verbose display shows how you can do it more semantically. This is relatively fast, and I'm using it to help merge a few hundred account settings at a time without a problem.