Home  >  Article  >  php教程  >  php获取数组中重复数据的两种方法

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

WBOY
WBOYOriginal
2016-06-13 11:44:181310browse

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

复制代码 代码如下:


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循环

复制代码 代码如下:


function FetchRepeatMemberInArray($array) {
    $len = count ( $array );
    for($i = 0; $i         for($j = $i + 1; $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 );
?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn