Try it like this:
if ( $query->have_posts() ) {
$categories = $category_ids = array();
while ( $query->have_posts() ) {
$query->the_post();
foreach ( ( get_the_category() ) as $category ) {
if ( ! in_array( $category->term_id, $category_ids ) ) {
$category_ids[] = $category->term_id;
$categories[] = $category;
}
}
};
}
get_the_category()
returns an array of objects. I didn’t check the in_array
documentation, but I suspect it doesn’t include object matching. $category_ids
is an array of just the ids used for comparison.