Home > Backend Development > PHP Tutorial > PHP获取数组中重复最多的元素的实现方法_php技巧

PHP获取数组中重复最多的元素的实现方法_php技巧

PHP中文网
Release: 2016-05-16 20:32:19
Original
1651 people have browsed it

本文实例讲述了PHP获取数组中重复最多的元素的实现方法。分享给大家供大家参考。具体方法如下:

 代码如下:

<?php  
/**  
 *   
 * Created on 2014-4-1  
 * @param   array $array  
 * @param   int [optional] $length  
 * @return  array  
 */  
function mostRepeatedValues($array,$length=0){  
    if(emptyempty($array) or !is_array($array)){  
        return false;  
    }  
    //1. 计算数组的重复值  
    $array = array_count_values($array);  
    //2. 根据重复值 倒排序  
    arsort($array);  
    if($length>0){  
        //3. 返回前 $length 重复值  
        $array = array_slice($array, 0, $length, true);  
    }  
    return $array;  
}  
$array = array(1, 1, 1, 54, 3,4, 3,4, 3, 14, 3,4, 3,7,8,9,12,45,66,5,7,8,9,2,45);  
$counts=mostRepeatedValues($array,5);  
print_r($counts);  
/*输出结果为:
Array  
(  
    [3] => 5  
    [4] => 3  
    [1] => 3  
    [9] => 2  
    [45] => 2  
)  
*/  
?>
Copy after login

以上就是PHP获取数组中重复最多的元素的实现方法_php技巧的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template