Group posts by attachment meta key

This is really more of a php/html question as this problem comes up outside of WordPress. What you want to do is check the current meta name against the previous one, and if it’s different, then you echo the header. You’re already pulling all the posts you need in one go, so it’s something like:

$currentGroup = "";
foreach ($posts as $post) {
  setup_postdata($post);
  $grouping = get_field('grouping');
  if ($grouping != $currentGroup) {
    if ($currentGroup != "") {
      echo "</ul>";
    }
    echo "<h2>" . $grouping . "</h2><ul>";
  }
  $currentGroup = $grouping;
  echo "<li><a href="" . the_permalink() . "">" . the_title() . "</a></li>";
}

Cheers.