我正在尝试从数组中删除重复项。如下所示,代码中的结果列表包含两个Sugar和Coffee事件。如何有效地从列表中删除重复项? (这个代码实际上要长得多,并且包含400多个元素)。
<?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>";
}
?>
非常感谢你
答案 0 :(得分:5)
使用array_unique函数从数组中删除重复值。
答案 1 :(得分:3)
试试这个,
$FoodList=array_unique($FoodList);
if(!empty($FoodList))
{
$str="<ul>";
foreach ($FoodList as $key => $value)
{
$str.="<li>" . $value . "</li>";
}
$str.= "</ul>";
echo $str;
}