PHP删除数组中的重复项

PHP删除数组中的重复项

问题描述:

I am trying to remove duplicates from an array. As you can see below, the resulting list from the code contains two incidents of Sugar and Coffee. What can I do to effectively remove the duplicates from the list? (The code for this is actually much longer, and includes over 400 elements).

<?php    
     $FoodList = array();
     $zb = Milk
     $cd = Bread
     $dc = Orange
     $ce = Apple
     $ec = KiwiFruit
     $cg = GrapeFruit
     $gc = Cucumber
     $ch = Biscuit
     $hc = Caramel
     $dv = Juice
     $ci = SoftDrink
     $ic = Banana
     $cj = Tea
     $cl = Sugar
     $jc = Coffee 
     $ck = Yoghurt
     $kc = Pizza Base
     $lc = Tuna

     if ($_POST['Dairy'] == 'Yes') { //Radio check box
         array_push($FoodList, $zb, $cd, $dc, $ce, $ec);
     }
     if ($_POST['GlutenFree'] == 'Yes') {
         array_push($FoodList, $cg, $gc, $ch, $hc, $dv);
     }
     if ($_POST['Fruit'] == 'Yes') {
         array_push($FoodList, $ci, $ic, $cj, $jc, $cl);
     }
     if ($_POST['Sweets'] == 'Yes') {
         array_push($FoodList, $jc, $ck, $kc, $cl, $lc);    
     }
     foreach ( $FoodList as $key => $value ) {
         echo "<li>" . $value . "</li>";
     }
     echo "</ul>";
}
?>

Thankyou so much

我正在尝试从数组中删除重复项。 如下所示,代码中的结果列表包含两个Sugar和Coffee事件。 如何有效地从列表中删除重复项? (这个代码实际上要长得多,并且包含400多个元素)。 p>

 &lt;?php 
 $ FoodList = array(); 
 $ zb = Milk 
 $ cd = Bread 
 $ dc = Orange 
 $ ce =  Apple 
 $ ec = KiwiFruit 
 $ cg = GrapeFruit 
 $ gc = Cucumber 
 $ ch = Biscuit 
 $ hc = Caramel 
 $ dv = Juice 
 $ ci = SoftDrink 
 $ ic = Banana \  n $ cj = Tea 
 $ cl = Sugar 
 $ jc = Coffee 
 $ ck = Yoghurt 
 $ kc = Pizza Base 
 $ lc = Tuna 
 
 if($ _POST ['Dairy'] =  ='是'){//收音机复选框
 array_push($ FoodList,$ zb,$ cd,$ dc,$ ce,$ ec); 
} 
 if($ _POST ['GlutenFree'] ==  '是'){
 array_push($ FoodList,$ cg,$ gc,$ ch,$ hc,$ dv); 
} 
 if($ _POST ['Fruit'] =='是'){\  n array_push($ FoodList,$ ci,$ ic,$ cj,$ jc,$ cl); 
} 
 if($ _POST ['Sweets'] =='是'){
 array_push($ FoodList,  $ jc,$ ck,$ kc,$ cl,$ lc);  
} 
 foreach($ FoodList as $ key =&gt; $ value){
 echo“&lt; li&gt;”  。  $ value。  “&lt; / li&gt;”; 
} 
 echo“&lt; / ul&gt;”; 
} 
?&gt; 
  code>  pre> 
 
 

非常感谢你 p> div>

Try this,

$FoodList=array_unique($FoodList);
if(!empty($FoodList))
{
    $str="<ul>";
    foreach ($FoodList as $key => $value)
    {
       $str.="<li>" . $value . "</li>";
    }
    $str.= "</ul>";
    echo $str;
}

Use array_unique function to remove duplicate values from an array.