Attach previously uploaded image to post – current code has unexpected results

Attachment is just post_parent value of the attachment post object, you can update that via wp_update_post:

foreach( $gallery_array as $value ) {
    $the_post = array(
        'ID'            => $value,
        'post_parent'   => $target_post_id,
    );
    wp_update_post( $the_post );
}