I’ve taken your code and refactored it. Your nested-for-loops arent the ideal way to go about this.
Also, I’ve used your code and the meta key names exactly as you supplied them, so please double-check they’re correct. Some of them are prefixed with the_
and then sometimes not. It’s strange, but that’s what you supplied.
Try the code below to see if you get just 1 of each.
<?php
$page_id = get_the_ID();
$related_args = [
'the_color' => get_field( 'color', $page_id ),
'the_background' => get_field( 'background', $page_id ),
'the_lastname' => get_field( 'lastname', $page_id )
];
$content="";
foreach ( $related_args as $meta_key => $meta_value ) {
$content .= $meta_value; //to know the post after it are from that custom post
$posts = get_posts( [
'post_type' => 'myposttype',
'orderby' => 'rand',
'meta_key' => $meta_key,
'meta_value' => $meta_value,
'numberposts' => 1,
] );
if ( !empty( $posts ) ) {
$postID = current( $posts )->ID;
$content .= sprintf( '<ul><li><a href="%s"><div class="post-image">%s</div><div class="post-title">%s</div></a></li></ul>',
get_permalink( $postID ),
get_the_post_thumbnail( $postID ),
get_the_title( $postID )
);
}
else {
$content .= 'no posts found';
}
}
echo $content;