Merge two (or more) arrays and keep values that are highest?

天大地大妈咪最大 提交于 2019-12-25 10:49:31

问题


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 |

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.


回答1:


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')



回答2:


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']




回答3:


Had to do something similar recently in PHP:

  $new_array = array();
  foreach ($array_second as $key => $value) {
    if ($array_first[$key] > $array_second[$key]) {
      $new_array[$key] = $array_first[$key];
    }
    else {
      $new_array[$key] = $array_second[$key];
    }
  }

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.



来源:https://stackoverflow.com/questions/3231105/merge-two-or-more-arrays-and-keep-values-that-are-highest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!