If what I understand from your question is correct. You have a post that categorized in multiple categories and subcategories. I have already made the same in a website. use these following code bellow so a sub categories will displayed after the parent category.
//first part
$allcats = get_the_category();
$parent_id = $all_ids = array();
foreach ($allcats as $cats) {
//get all category id first
$all_ids[] = $cats->term_id;
// get top parent category
if ($cats->category_parent === 0 ) {
$parent_id[] = $cats->term_id;
}
}
//second part
$separator=" » ";
$term_ids = implode( ',' , $all_ids );
$hiearchy_cat="";
foreach ($parent_id as $parents) {
$parent_name = get_cat_name($parents);
$parent_link = get_category_link($parents);
$parent_cat="<span class="parent"><a href="".$parent_link.'">'.$parent_name.'</a></span>';
//get all sub category with certain ids
$child_cats = wp_list_categories(
array(
'child_of' => $parents,
'title_li' => '',
'style' => 'none',
'echo' => false,
'taxonomy' => 'category',
'include' => $term_ids,
)
);
$child_cats = rtrim( trim( str_replace( '<br />', $separator, $child_cats ) ), $separator );
$hiearchy_cat .= '<b>'.$parent_cat.'</b> » '.$child_cats.'<br>';
}
//last output
echo $hiearchy_cat;
Hope it helps