开发者

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开发者_如何学JAVA         | 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.


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜