如何防止重复数据显示在循环PHP

时间:2019-01-10 10:23:18

标签: php sql loops

我有一个脚本来显示产品的相关产品。这些显示在购物车中,该购物车可以具有多个产品,因此,例如,如果产品1和产品2具有相同的相关产品,则所有这些产品都显示两次。

我只需要显示一次,该怎么办?

我当前的脚本:

$relatedarticles = '
SELECT
  cnt.catid,
  cnt.title AS content_title,
  cnt.alias AS content_alias,
  cnt.introtext,
  cnt.images,
  cnt.state,
  f.field_id,
  f.item_id,
  f.value,
  cat.title AS cat_title,
  cat.id
FROM snm_content cnt
  LEFT JOIN snm_fields_values f
  ON cnt.id = f.item_id
  LEFT JOIN snm_categories cat
  ON cnt.catid = cat.id
WHERE cnt.alias = "'.$conn->real_escape_string($cartproduct1['alias']).'"
AND field_id = 10
AND cnt.state = 1';
$relatedarticlescon = $conn->query($relatedarticles);
while($relatedarticles = $relatedarticlescon->fetch_assoc()){

  $relhtml .= '<div class="relatedwrapper">';
  $rel = '
  SELECT
   cnt.title AS content_title,
   cnt.alias AS content_alias,
   cnt.introtext,
   cnt.images,
   cnt.state,
   cat.title AS cat_title,
   cat.alias AS cat_alias
  FROM snm_content cnt
    LEFT JOIN snm_categories cat
    ON cnt.catid = cat.id
  WHERE cnt.id = "'.$conn->real_escape_string($relatedarticles['value']).'"
  AND cnt.state = 1';
  $relcon = $conn->query($rel);

  while($rel = $relcon->fetch_assoc()){

    $relimage = $rel['images'];
    $relimg = json_decode($relimage);

    if ($relimg->image_intro != "") {
      $imgrel = 'cms/'.$relimg->image_intro;
    }else{
      $imgrel = 'images/_bad_noimg.jpg';
    }

    $relhtml .= '
    <div class="col-md-3">
      <a class="relateda" href="'.$rel['cat_alias'].'-huren/'.$rel['content_alias'].'">
        <div class="relatedcontent">
          <span class="titlespan">'.$rel['content_title'].'</span>
          <span class="catspan">'.$rel['cat_title'].'</span>
          <img src="'.$imgrel.'">
        </div>
      </a>
    </div>';
  }
}

$relatedarticles['value']包含所有相关的产品ID。

1 个答案:

答案 0 :(得分:0)

一个简单的列表可能会做得很好:

$shownRelated = array();
while($rel = $relcon->fetch_assoc()){
   if (isset($shownRelated[$relatedarticles['value']])) {
      continue;
   }
   $shownRelated[$relatedarticles['value']] = true;

...

}

这只会创建显示给客户的产品列表,并防止第二次(或第n次)显示该产品。