Why is this loop necessary? Can't you make it part of previous loop while creating the `$criteria` array?