合并两个(或更多)数组并保留最高的值? [英] Merge two (or more) arrays and keep values that are highest?
问题描述
我有一个基于权限/组的设置,正在尝试合并结果.例如,一个用户可能与四个组相关联:
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 | test@test.com | 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 |
我希望获取这四行的结果(从数据库查询中存储为数组),并将其合并为一个数组,如下所示:
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 |
每个数组中的最大值成为组合数组中的值.如果100条记录中有1条是"2",其余的是"1"或"0",那么我需要在结果中添加"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.
我看过array_merge,但是它根据指定给函数的变量的顺序保留值.
I've looked at array_merge, but it keeps the value depending on the order of variables specified to the function.
推荐答案
也许您希望数据库已经对此进行处理:
Maybe you want this handled already by the DB:
SELECT MAX(perm1), MAX(perm2), MAX(perm3), MAX(perm4), MAX(perm5), MAX(perm6), MAX(perm7)
FROM group_perm_linking_table
WHERE group IN ('gr1', 'gr2', 'gr3', 'gr4')
这篇关于合并两个(或更多)数组并保留最高的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!