I need help in removing or skipping duplicate data from foreach array, i try to use array_unique() but it doesn’t help.
here’s my code.
<?php if(is_cart()){ foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { $term_name = get_the_terms( $cart_item['product_id'], 'product_cat' ); foreach($term_name as $idterm){ if($idterm->parent == 0){ $parentcat = $idterm->description; } $term_prid = $idterm->term_id; } $rootId = end( get_ancestors( $term_prid, 'product_cat' ) ); $root = get_term( $rootId, 'product_cat' ); if(!empty($root->description)){ echo '<div class="club-information"><div class="club-record"><p>'.$root->description.'</p></div></div>'; } } if(!empty($parentcat)){ echo '<div class="club-information"><div class="club-record"><p>'.$parentcat.'</p></div></div>'; } } ?>
if i have more than 2 products of same category in cart it repeat the same data, which should not.
this is what i get from print_r($term_prid)
91 91 13
How can i get
91 13
Advertisement
Answer
Save the IDs you’ve seen in an array, and check against that.
if(is_cart()){ $seen_ids = []; foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { $term_name = get_the_terms( $cart_item['product_id'], 'product_cat' ); foreach($term_name as $idterm){ if (in_array($idterm->term_id, $seen_ids)) { continue; } $seen_ids[] = $idterm->term_id; if($idterm->parent == 0){ $parentcat = $idterm->description; } $term_prid = $idterm->term_id; } $rootId = end( get_ancestors( $term_prid, 'product_cat' ) ); $root = get_term( $rootId, 'product_cat' ); if(!empty($root->description)){ echo '<div class="club-information"><div class="club-record"><p>'.$root->description.'</p></div></div>'; } } if(!empty($parentcat)){ echo '<div class="club-information"><div class="club-record"><p>'.$parentcat.'</p></div></div>'; } }