显示逗号分隔值的名称

时间:2015-04-23 03:18:30

标签: php mysql foreach

我对文章数据有一个查询,其中包含一个名为products的mysql列。该字段包含如此2,20,12的值。这些数字代表与文章相关的产品行的ID。

我需要弄清楚如何在每篇文章下展示产品而不会产生每个结果的重复。

     $sql5="SELECT * FROM #__content WHERE catid=$iconcategoryid";
     $db->setQuery($sql5);
     $articles= $db->loadObjectlist();
     foreach($articles as $article){ 

        $product_ideez = $article->products;

        $sql6="SELECT * FROM #__products_products WHERE id IN($product_ideez)";
        $db->setQuery($sql6);
        $products= $db->loadObjectlist();

        foreach ($products as $product) {

        $productArray .= '<span class="badge">'.$product->name.'</span>';

        }



    // my html output is here
    // i am getting duplication on the output of the product names

    echo '<h1>'.$article->title.'</h1>';
    echo '<hr/>';
    echo $productArray; // this works but then is multiplied for each new entry against the first query.

   }

我希望我的问题很清楚。

http://imgur.com/E0BTlUo

干杯 约翰

2 个答案:

答案 0 :(得分:1)

您需要在使用前初始化$ productArray。将其添加到第一个foreach的最开头:

$productArray = "";

答案 1 :(得分:0)

      $sql5="SELECT * FROM #__content WHERE catid=$iconcategoryid";
      $db->setQuery($sql5);
      $articles= $db->loadObjectlist();
      foreach($articles as $article){ 
        $productArray='';
         $product_ideez = $article->products;

         $sql6="SELECT * FROM #__products_products WHERE id IN($product_ideez)";
         $db->setQuery($sql6);
         $products= $db->loadObjectlist();

         foreach ($products as $product) {

         $productArray .= '<span class="badge">'.$product->name.'</span>';

         }



     // my html output is here
     // i am getting duplication on the output of the product names

     echo '<h1>'.$article->title.'</h1>';
     echo '<hr/>';
     echo $productArray; // this works but then is multiplied for each new entry against the first query.

    }