从数组中删除重复项

发布于 2024-10-17 17:13:24 字数 2465 浏览 1 评论 0原文

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

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

如果我打印出数组:

print_r($items_thread);

我会得到这个:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => [email protected]
        )

    [1] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => [email protected]
        )

    [2] => Array
        (
            [RecipientID] => 1
            [RecipientScreenname] => Lau T
            [RecipientFirstname] => TK
            [RecipientEmail] => [email protected]
        )

)

但我想删除数组中的重复项,所以我使用 array_unique

print_r(array_unique($items_thread));

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

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => [email protected]
        )

)

理想情况下,我认为它应该返回这个:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => [email protected]
        )

    [1] => Array
        (
            [RecipientID] => 1
            [RecipientScreenname] => Lau T
            [RecipientFirstname] => TK
            [RecipientEmail] => [email protected]
        )

)

我该怎么做才能让它正确?我是否使用了错误的 PHP 语法/默认函数?

I use the line of code below to loop through a table in my database:

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

And if I print the array out:

print_r($items_thread);

I will get this:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => [email protected]
        )

    [1] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => [email protected]
        )

    [2] => Array
        (
            [RecipientID] => 1
            [RecipientScreenname] => Lau T
            [RecipientFirstname] => TK
            [RecipientEmail] => [email protected]
        )

)

But I want to get rid of the duplicate items in the array, so I use array_unique

print_r(array_unique($items_thread));

I get the weird result below which is not quite I am looking for:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => [email protected]
        )

)

Ideally, I think it should return this:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => [email protected]
        )

    [1] => Array
        (
            [RecipientID] => 1
            [RecipientScreenname] => Lau T
            [RecipientFirstname] => TK
            [RecipientEmail] => [email protected]
        )

)

What shall I do to get it right? Have I used the wrong PHP syntax/default function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

荒芜了季节 2024-10-24 17:13:24

array_unique 函数将为您完成此操作。您只需要添加 SORT_REGULAR 标志:

$items_thread = array_unique($items_thread, SORT_REGULAR);

但是,如 bren 建议,如果可能的话,您应该在 SQL 中执行此操作。

The array_unique function will do this for you. You just needed to add the SORT_REGULAR flag:

$items_thread = array_unique($items_thread, SORT_REGULAR);

However, as bren suggests, you should do this in SQL if possible.

你在我安 2024-10-24 17:13:24

过滤掉 SQL 查询中的重复项会更好。添加一个获取唯一收件人 ID 的约束

You'd be much better off filtering out the duplicates in the SQL query. add a constraint which fetches a UNIQUE recipientID

凑诗 2024-10-24 17:13:24

要删除重复值,我们可以使用 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
)

To remove duplicate values then we can use array_unique() function. The functionality of it is to accept an array and returns another array without duplicate values.

General description of array_unique() is given below:

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 

Example 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));
?>

Output:

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
)
北城孤痞 2024-10-24 17:13:24

试试这个:

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

输出以下内容:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => [email protected]
        )

    [2] => Array
        (
            [RecipientID] => 1
            [RecipientScreenname] => Lau T
            [RecipientFirstname] => TK
            [RecipientEmail] => [email protected]
        )
)

但我也认为你应该在数据库中实现这个。另外,检查我的其他答案和解决方案。

Try this:

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

Outputs the following:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => [email protected]
        )

    [2] => Array
        (
            [RecipientID] => 1
            [RecipientScreenname] => Lau T
            [RecipientFirstname] => TK
            [RecipientEmail] => [email protected]
        )
)

But I also think you should implement this in your database. Also, check my other answer and solutions.

梨涡少年 2024-10-24 17:13:24

您可以使用此代码,希望它对您有所帮助。它完全可以工作:

$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); 

You can use this code and I hope it will help you. It's completely working:

$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); 
锦爱 2024-10-24 17:13:24

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

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

You can use the regular php arrays to achieve this.

$newArray = array();
foreach ($origArray as $user)
{
   $newArray[$user['RecipientID']] = $user;
}
转角预定愛 2024-10-24 17:13:24

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

$resultArray = uniqueAssocArray($actualArray, 'RecipientID');

function uniqueAssocArray($array, $uniqueKey) {
if (!is_array($array)) {
    return array();
}
$uniqueKeys = array();
foreach ($array as $key => $item) {
    $groupBy=$item[$uniqueKey];
    if (isset( $uniqueKeys[$groupBy]))
    {
        //compare $item with $uniqueKeys[$groupBy] and decide if you 
        //want to use the new item
        $replace= false; 
    }
    else
    {
        $replace=true;
    }
    if ($replace) $uniqueKeys[$groupBy] = $item;   
}
return $uniqueKeys;

}

Please check below code, I hope this is help full for you.

$resultArray = uniqueAssocArray($actualArray, 'RecipientID');

function uniqueAssocArray($array, $uniqueKey) {
if (!is_array($array)) {
    return array();
}
$uniqueKeys = array();
foreach ($array as $key => $item) {
    $groupBy=$item[$uniqueKey];
    if (isset( $uniqueKeys[$groupBy]))
    {
        //compare $item with $uniqueKeys[$groupBy] and decide if you 
        //want to use the new item
        $replace= false; 
    }
    else
    {
        $replace=true;
    }
    if ($replace) $uniqueKeys[$groupBy] = $item;   
}
return $uniqueKeys;

}

野味少女 2024-10-24 17:13:24
$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       
    }
}
$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       
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文