the sample data, which was probably defined to demonstrate this issue, ran out of users that could perform role id 7 before reaching the role id 7 evaluation. when this occurs, you need to be willing to accept a less than ideal solution, by introducing a random element into the process.
a general method would be to take the top n (n = 1, 2, 3, ...) initial entries in the $roles_array, shuffle it/them, and produce a 'current' array consisting with those shuffled entries and the remaining unshuffled entries and try to produce a solution using that data that satisfies all the roles that have required importance. repeat the shuffling for each n value at least n squared times to give the shuffling a chance to produce unique results (computers are not very good at doing things randomly.) after each shuffle, check if the key order has already been tried, by remembering the composite key sequences, that have been evaluated, in an array, by imploding the keys with some unique character, e.g. a | or similar. if the key order has already been tried, skip the current evaluation loop.