天天看點

php 數組中重複值,php擷取數組中重複資料的函數

php擷取數組中重複資料的函數

PHP

#數組 #重複資料 #函數2012-10-20 10:00

(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 < $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數組函數請看:http://yige.org/php/ref_array.php

相關文章