The result of calling:
$username = $DB->get_record('user', array('id' => $userid), 'username');
Is an object with just a single member variable: $username->username
If you just want to retrieve the username directly, then you can do:
$username = $DB->get_field('user', 'username', ['id' => $userid]);
However, if you are doing this for each user, then this will result in a lot of extra database calls, which can add a large overhead to your page.
Ideally, you should be loading all the usernames at once, to avoid this overhead.