Fix incorrect related posts code snippet

Your first problem:

Try to write down what you want to do: You do not want to print posts that are already printed.

So you have to remember what posts are already printed. In PHP normally an array is a good solution to remember things that are already done. Let’s add an array:

$printed_posts = array( $current_post );

The ID of the current post is added because this post should be excluded always.

Now you have to add the printed posts to that array too:

array_push( $printed_posts, $post->ID );

But what to do with that array? You want to exclude the already printed posts from your query. That’s easy because you got an option exclude= to do that. So lets exclude the already printed posts from the query:

$posts = get_posts('numberposts=5&category='. $category->term_id . '&exclude=" . implode( ",', $current_post ); // excludeded posts as comma separeted list

Befor continue reading, try to insert this advice into your code at the right place. That’s the way you will learn how to solve problems.

If you only search for an copy&paste solution, here we go (untested, I don’t like such a code mess):

<?php

function related_posts() {
    if (is_single()) {
        global $post;
        $current_post = $post->ID;
        $categories = get_the_category();

        foreach ($categories as $category) {

        $printed_posts = array( $current_posts );

        ?>
            <div class="my-related-posts">
                <h4>Related Posts</h4>
                <ul>
                    <?php
                    $posts = get_posts('numberposts=5&category='. $category->term_id . '&exclude=" . implode( ",', $current_post );

                    foreach($posts as $post) {
                        array_push( $printed_posts, $post->ID );
                        ?><li><a href="https://wordpress.stackexchange.com/questions/77874/<?php the_permalink(); ?>"><?php the_title(); ?></a></li><?php
                    }
                    ?>

                </ul>
            </div>
        <?php

        }

        wp_reset_query();

    }
}

add_action( 'genesis_after_post_content', 'related_posts' );

For your second problem, you can ask Google or any other search engine with something like ‘get post category’ or ‘get post parent category’