Taxonomy , subtaxonomy,child taxonomy of a product woocommerce

Based on this answer, here is my function to get all your terms in an array :

function get_term_ancestors($post_id, $taxonomy){
    // Declare the array where we are going to store the terms
    $ancestors = array();
    // start from the current term
    $parent  = array_shift(get_the_terms($post_id,$taxonomy));
    // climb up the hierarchy until we reach a term with parent="0"
    while ($parent->parent != '0'){
        $term_id = $parent->parent;

        $parent  = get_term_by( 'id', $term_id, $taxonomy);
        $ancestors[] = $parent;
    }
    return $ancestors;
}

Use as follow :

$ancestors = get_term_ancestors(123,'product_cat');

So with this function, your top level term will be :

$ancestors[count($ancestors)-1] // or array_pop($ancestors);

and your second top level parent will be

$ancestors[count($ancestors)-2] // or another array_pop($ancestors)

Please also note than you should check isset($ancestors[count($ancestors)-2]) before trying to access it

Warning : This will only work for products which are in one term. This function does not handle multiple terms