@kayinja.denis,
Basically, what I'm saying is taking the foreach loop and converting it into your database view. Then when you call the database view it would already have your results. Currently, you run a database view then run multiple foreach loops to populate the mark detail. My way would be one database view which would already include your mark detail.