Custom Post Type and Taxonomy Loop Output Is Wrong

I’m trying to loop through the various posts that fit within my custom taxonomy: “industries”. The post type is custom (type: “member”) and so I’ve been trying to build a loop that outputs the current taxonomy header and then the businesses that have that category assigned to them. Like so:

Business Services:

Company A

Construction Services:

Company B

Except with my current code it outputs all businesses under each heading. I’m sure the logic is just not quite right, but I am trying to figure out what I’ve done wrong and I can’t see it.

My archive-members.php code:

  $categories = get_terms('industries', array(
    'hide_empty' => 1
  ));

  foreach($categories as $category) {

    $post_array = get_posts(array('post_type' => 'members', 'industries' => $category->name));
    setup_postdata($post_array);
    ?>

    <h1><?php echo $category->name; ?></h1>

    <?php
      if(have_posts()):
        while(have_posts()):
          the_post();
    ?>

    <p> <?php the_title(); ?> </p>

    <?php
    endwhile; endif;
    wp_reset_postdata();
  }

Solutions Collecting From Web of "Custom Post Type and Taxonomy Loop Output Is Wrong"

I would do it like this, with WP Query. As @Milo pointed out, the issue is that the above code is running the main WP loop on each successive iteration and that loop isn’t picking up on the custom query. Creating a loop from WP Query will yield the right results.

<?php 

$categories = get_terms('industries', array(
    'hide_empty' => 1
));

foreach($categories as $category) { ?>
    <h1><?php echo $category->name; ?></h1>
    <?php
    // WP_Query arguments
    $args = array(
        'post_type'              => array( 'members' ),
        'industries'          => $category->name,
    );

    // The Query
    $query = new WP_Query( $args );

    // The Loop
    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
            $query->the_post();
            ?>
            <p> <?php the_title(); ?> </p>
            <?php
        }
    } else {
        // no posts found
    }

    // Restore original Post Data
    wp_reset_postdata();
}
    ?>