To sort hierarchically, try adding a sorting function to your functions.php (or plugin).
// This will sort and place everything in the $into array
function sort_terms_hierarchically(Array &$cats, Array &$into, $parentId = 0) {
foreach ($cats as $i => $cat) {
if ($cat->parent == $parentId) {
$cat->posts = array();
$into[$cat->term_id] = $cat;
unset($cats[$i]);
}
}
foreach ($into as $topCat) {
$topCat->children = array();
sort_terms_hierarchically($cats, $topCat->children, $topCat->term_id);
}
}
Now on the display side, you could grab all of your categories and display them with the parent name second.
$terms = get_the_terms( $product->get_id(), 'product_cat' );
if ( $terms ) {
$listItems="";
$sortedTerms = array(); // empty array to hold the sorted terms
sort_terms_hierarchically( $terms, $sortedTerms ); // sort everything
foreach( $sortedTerms as $parent) {
if ( empty( $parent->children ) ) continue;
foreach( $parent->children as $child ) {
$listItems .= '<li>' . $child->name . ', ' . $parent->name . '</li>';
}
}
}
// Display the list
if ( !empty( $listItems ) ) {
echo '<ul>' . $listItems . '</ul>';
}
Hope this better answers your question!