php query in loop echo's duplicates -


heres loop lists products purchased (digital access pass) user. wish have wordpress posts featured image show beside each product. however, there no solid relation between dap product , wordpress post. work around make sure dap product has same name/title wp post. problem is, using code have far (between hash tags), runs queries each dap product in loop , therefore spits out duplicates x amount of dap products.

so if theres 3 dap products, , 2 of them have matching title wp posts, result looks this...

16521652

hope makes sense. appreciate assistance.

global $wpdb;  //loop on each product list foreach ($userproducts $userproduct) {     if($productid != "all") {         $productidarray = explode(",",$productid);          //if( $userproduct->getproduct_id() != $productid ) {         if( !in_array($userproduct->getproduct_id(), $productidarray) ) {             continue;         }     }      $product = dap_product::loadproduct($userproduct->getproduct_id());      $expired = false;     if($user->hasaccessto($product->getid()) === false) {         $expired = true;     }        //##########################################################################      /*1.get post id post title if know title or title variable*/      $postid = $wpdb->get_var( "select id $wpdb->posts post_title = '" . $product->getname() . "'" );     $postname = $wpdb->get_var( "select post_title $wpdb->posts post_title = '" . $product->getname() . "'" );      if ($product->getname() == $postname):     echo $postid;     endif;      /*2.use get_post($post_id) whatever want echo*/     $getpost= get_post($postid);     $postcontent= $getpost->post_content;     echo $postcontent;      //##########################################################################      $content .= '</div>';     $content .= '<br/><br/>'; } //end foreach  return $content; 

a quick workaround store retrieved post names/ids in array; avoid duplicates, before storing each value, check if stored:

if (in_array($postid,$values)==false) $values[] = $postid; 

then, after retrieving values (i.e. after loop), proceed posts , post contents.

edit:

would mind telling me how store values in array?

before loop, initialize array:

$values = array(); 

after retrieving $postid , $postname, , checking product's name equals post name, put value in array:

if (in_array($postid,$values)==false) $values[] = $postid; 

after loop ends, have id's of posts looking for. iterate $values array using foreach loop , use them.


Comments