Never mind, I have solved it myself. The solution is to use an recursive algorithm that takes an multidim array as an argument as well as the row count.