php获取数组中重复数据的两种方法

yipeiwu_com7年前PHP代码库

(1)利用php提供的函数,array_unique和array_diff_assoc来实现

复制代码 代码如下:

<?php
function FetchRepeatMemberInArray($array) {
    // 获取去掉重复数据的数组
    $unique_arr = array_unique ( $array );
    // 获取重复数据的数组
    $repeat_arr = array_diff_assoc ( $array, $unique_arr );
    return $repeat_arr;
}

// 测试用例
$array = array (
        'apple',
        'iphone',
        'miui',
        'apple',
        'orange',
        'orange' 
);
$repeat_arr = FetchRepeatMemberInArray ( $array );
print_r ( $repeat_arr );
?>

(2)自己写函数实现这个功能,利用两次for循环

复制代码 代码如下:

<?php
function FetchRepeatMemberInArray($array) {
    $len = count ( $array );
    for($i = 0; $i < $len; $i ++) {
        for($j = $i + 1; $j < $len; $j ++) {
            if ($array [$i] == $array [$j]) {
                $repeat_arr [] = $array [$i];
                break;
            }
        }
    }
    return $repeat_arr;
}

// 测试用例
$array = array (
        'apple',
        'iphone',
        'miui',
        'apple',
        'orange',
        'orange' 
);
$repeat_arr = FetchRepeatMemberInArray ( $array );
print_r ( $repeat_arr );
?>

相关文章

php.ini中的request_order推荐设置

今天刚刚安装dede,安装完成由一条错误信息(PHP 5.3 and above) Please set 'request_order' ini value to include C,G...

PHP中file_get_contents高級用法实例

本文实例讲述了PHP中file_get_contents高级用法,分享给大家供大家参考。具体分析如下: 首先解决file_get_contents的超时问题,在超时返回错误后就象js中的...

PHP中CURL的CURLOPT_POSTFIELDS参数使用细节

在通常情况下,我们使用 CURL 来提交 POST 数据的时候,我们已经习惯了这样的写法:复制代码 代码如下:curl_setopt( $ch, CURLOPT_POSTFIELDS,$...

php字符集转换

PHP通过iconv将字符串从GBK转换为UTF8字符集。 1. iconv()介绍 iconv函数可以将一种已知的字符集文件转换成另一种已知的字符集文件。例如:从GB2312转换为U...

用PHP编写和读取XML的几种方式

一.使用DOM生成和读取XML文件 实例一: 复制代码 代码如下: <?php //Creates XML string and XML document using the DO...