【问题标题】:Remove duplicate items from an array [duplicate]从数组中删除重复项[重复]
【发布时间】:2011-06-29 12:21:03
【问题描述】:

我使用下面的代码行循环访问我的数据库中的一个表:

$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 语法/默认函数?

【问题讨论】:

  • array_unique() 将所有内容简化为单个数组,因为它将您的内部数组作为字符串进行比较,所有这些都评估为Array。所以每个数组都被认为是相同的。此外,来自manual:“请注意,array_unique() 不适用于多维数组。”
  • 感谢您的建议 - 选择 DISTINCT RecipientID。它不会返回我需要的结果,即使我可以从中获得独特的价值......你可以看看我之前在这里发布的帖子 - stackoverflow.com/questions/5032645/… 谢谢。

标签: php arrays duplicates array-unique


【解决方案1】:

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

$items_thread = array_unique($items_thread, SORT_REGULAR);

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

【讨论】:

  • 这个我找了差不多半天了!
【解决方案2】:

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

【讨论】:

  • SELECT DISTINCT RecipientID ...
  • @BoltClock 谢谢...你能解释一下为什么这种方式比array_unique() 更好吗?
  • @CJ Ramki:您只需选择您需要的行而不是从数据库中抓取所有内容并丢弃您不需要的行,从而减少资源浪费。
  • 那么,如果我有像this 这样的数组,array_unique() 将比较字符串ArrayArray 并产生结果?
【解决方案3】:

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

【讨论】:

    【解决方案4】:

    试试这个:

    $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 和解决方案。

    【讨论】:

    • 谢谢你! $items_thread = array_unique($items_thread, SORT_REGULAR) 怎么样?哪个返回与您的代码相同的结果?
    • @lauthiamkok:我从来没有这样做过,它真的返回相同的输出吗?如果是,那就太好了!
    • @lauthiamkok:我已阅读手册,该标志似乎提供了正确的结果,但请记住它仅在 PHP >= 5.2.9 中可用。
    • 谢谢。我在 php 5.3.x 上,我的直播也将在 5.3.x 上,所以我认为我很安全!非常感谢!
    【解决方案5】:

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

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

    【讨论】:

      【解决方案6】:

      您可以使用常规的 php 数组来实现这一点。

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

      【讨论】:

        【解决方案7】:

        $unique = array_keys(array_flip($array));

        它更快,而且它重置了数组键索引。

        来源http://php.net/manual/en/function.array-unique.php#89519

        这仅适用于简单数组。

        【讨论】:

          【解决方案8】:

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

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

          }

          【讨论】:

            【解决方案9】:
            $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       
                }
            }
            

            【讨论】:

              猜你喜欢
              • 2013-08-03
              • 2017-04-10
              • 2017-06-21
              • 2011-01-04
              相关资源
              最近更新 更多