从数组中删除重复的项目

时间:2011-02-18 00:25:02

标签: php arrays duplicates array-unique

我使用下面的代码行循环遍历数据库中的表:

$items_thread = $connection -> fetch_all($sql);

如果我打印出阵列:

print_r($items_thread);

我会得到这个:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => info@xx.com
        )

    [1] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => info@xx.com
        )

    [2] => Array
        (
            [RecipientID] => 1
            [RecipientScreenname] => Lau T
            [RecipientFirstname] => TK
            [RecipientEmail] => lau@xx.co.uk
        )

)

但是我想摆脱数组中的重复项,所以我使用array_unique

print_r(array_unique($items_thread));

我得到了下面的奇怪结果,这不是我想要的:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => info@xx.com
        )

)

理想情况下,我认为它应该归还:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => info@xx.com
        )

    [1] => Array
        (
            [RecipientID] => 1
            [RecipientScreenname] => Lau T
            [RecipientFirstname] => TK
            [RecipientEmail] => lau@xx.co.uk
        )

)

我该怎么做才能把它弄好?我使用了错误的PHP语法/默认函数吗?

8 个答案:

答案 0 :(得分:66)

array_unique功能会为您完成此操作。您只需要添加SORT_REGULAR标志:

$items_thread = array_unique($items_thread, SORT_REGULAR);

但是,如bren所示,如果可能,您应该在SQL中执行此操作。

答案 1 :(得分:6)

最好过滤出SQL查询中的重复项。添加一个获取UNIQUE recipientID

的约束

答案 2 :(得分:4)

要删除重复值,我们可以使用array_unique()函数。它的功能是接受一个数组并返回另一个没有重复值的数组。

array_unique()的一般描述如下:

General Format = array array_unique(array $array [, int $sort_flags=sort_string] )
Parameters     = array: Input array ->sort_flags:
    The second optional parameter is used to compare items as follows
         1. SORT_REGULAR - Normal
         2. SORT_NUMERIC - Numerically
         3. SORT_STRING - As
         4. string  SORT_LOCALE_STRING - As string, based on the current locale.
Return Value   = Another array without duplicate values 

示例1:

<?php
$array=array('cricket'=>11,'football'=>11,'chess'=>2);
echo"<br/><b>Initially the values of \$array is:</b><br/>";
var_dump($array);
echo"<br/><b>After removing the duplicates:</b><br/>";
print_r(array_unique($array));
?>

输出:

Initially the values of $array is:
array(3) {
  ["cricket"] => int(11)
  ["football"] => int(11)
  ["chess"] => int(2)
}

After removing the duplicates:
Array
(
    [cricket] => 11
    [chess] => 2
)

答案 3 :(得分:1)

试试这个:

$data = array_map('unserialize', array_unique(array_map('serialize', $data)));

输出以下内容:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => info@xx.com
        )

    [2] => Array
        (
            [RecipientID] => 1
            [RecipientScreenname] => Lau T
            [RecipientFirstname] => TK
            [RecipientEmail] => lau@xx.co.uk
        )
)

但我也认为你应该在你的数据库中实现它。此外,check my other answer和解决方案。

答案 4 :(得分:1)

您可以使用此代码,我希望它能为您提供帮助。它完全有效:

$array = array(1,1,2,3,4,4,4,5);
$temp=array();

for($i=0; $i<=count($array); $i++)
 {

    if($array[$i] != '')
    {
        for($j=$i+1; $j<=count($array); $j++ )
        {
            if($array[$i]==$array[$j])
            {
                $array[$j] = '';
            }
            else
            {
                $temp[$array[$i]]=$array[$i];
            }

         }

    }
}

print_r($temp); 

答案 5 :(得分:0)

您可以使用常规的php数组来实现此目的。

$newArray = array();
foreach ($origArray as $user)
{
   $newArray[$user['RecipientID']] = $user;
}

答案 6 :(得分:0)

请检查下面的代码,我希望这对你有帮助。

    <ListBox x:Name="AppBarMenu"
     Grid.Row="1"
     Canvas.ZIndex="1"
     ScrollViewer.HorizontalScrollMode="Enabled"
     ScrollViewer.HorizontalScrollBarVisibility="Visible"
     ScrollViewer.VerticalScrollBarVisibility="Disabled"
     ScrollViewer.VerticalScrollMode="Disabled"
     Background="{StaticResource BackgroundColorApp}"
     ItemTemplate="{StaticResource StackMenuItem}"
     ItemsSource="{Binding}"
     Style="{StaticResource ListBoxHorizontal}"
     ItemContainerStyle="{StaticResource ListBoxContainerStylePP}"
     Foreground="{StaticResource TBColorNonSelected}"
     SelectedIndex="{Binding SelectedIndex, ElementName=PetProtectorFrames, Mode=TwoWay}"
     Height="0"
     VerticalAlignment="Top"
     SelectionChanged="AppBarMenu_SelectionChanged">

 </ListBox>

}

答案 7 :(得分:0)

$res1       = mysql_query("SELECT * FROM `luggage` where r_bus_no='".$tour_id."' and `date1`='$date' AND `login_id`='".$_SESSION['login_id']."'");
}
/// create a array to store value
$city_arr   = array();
if(mysql_num_rows($res1)>0)
{
    while($row1 = mysql_fetch_array($res1))
    {

/// insert the value in array use the array_push function
            array_push($city_arr,$row1['r_to']);
    }

//// remove the duplicate entry in array use the array_unique function
    $a          = array_unique($city_arr);
    echo "<option value='' selected='selected'> -- Select City ---</option>";
    foreach($a as $b)
    {
    ?>
    <option value="<?php echo $b ;?>"><?php echo city($b); ?></option>
    <?php       
    }
}