A few seconds is probably a long time?
$j is not used in your script and has no effect on any of the code following it which is why it hasn't been changed and why you haven't noticed, is this causing other problems though?
As Barand points out, really you should look change the query which would allow you to arrange the results in descending order as well as joining all the queries together in one.
Barand:
for($j='2018';$j<=$maxdate;$j++) {
Should that have been:
for($j='2018';$j<=$maxdate;$j--) {