You don't really provide enough code to do this (ie what variable is table b's data stored in, assuming its already been queried). However I would hazard it would be something like the following (assuming table b's data is already queried and stored in $tableB as an array):
echo '
'.$r['id'].'
';
foreach($tableB as $b)
{
if ($b['ID'] == $r['id'])
{
echo ' '.$b['msg'].' ';
}
}
echo '
'
;
?>