Home  >  Article  >  Backend Development  >  php统计数组中相同元素个数的方法

php统计数组中相同元素个数的方法

WBOY
WBOYOriginal
2016-06-20 13:02:001748browse

php统计数组中相同元素个数的方法

关联数组一般不能进行分组统计,可以通过array_values()函数对数组元素进行分组统计!

$arr = array(
	'a'=>'java',
	'b'=>'php',
	'c'=>'java',
);
$arr = array_values($arr);  //返回数组所有的值,并建立数字索引
$arr1 = array();
 
foreach ($arr as $a){
	if (!isset($arr1[$a])){
		$arr1[$a] = 1;
	}else {
		$arr1[$a]++;
	}
}
 
echo "";
foreach($arr1 as $k=>$val){
	echo "";
}
echo "
$k$val
";

PHP 中的 array_count_values() 函数可以实现

array_count_values() 函数用于统计数组中所有值出现的次数。

本函数返回一个数组,其元素的键名是原数组的值,键值是该值在原数组中出现的次数。

array_count_values(array)

例如:

$a=array("Cat","Dog","Horse","Dog");

print_r(array_count_values($a));


输出:

Array ( [Cat] => 1 [Dog] => 2 [Horse] => 1 )


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