Refactoring. Extract method.
Added last test to ensure all is working well.
Refactoring. Collapsed the two branch if to one.
Refactoring. Removing local temporary variable.
Refactoring. Simplifying the syntax.
Refactoring. Removed inner for loop
Refactoring. Removed outer for loop.
Refactoring.
Added variable for innermost foreach