Home >php教程 >php手册 >php 获取数组中重复数据

php 获取数组中重复数据

WBOY
WBOYOriginal
2016-06-13 10:52:361467browse

两天前,需要用到找出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         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