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

WBOY
Release: 2016-06-20 13:02:00
Original
1928 people have browsed it

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 "<table border=&#39;1&#39; cellpadding=&#39;5&#39;>";
foreach($arr1 as $k=>$val){
	echo "<tr><td>$k</td><td>$val</td></tr>";
}
echo "</table>";
Copy after login

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

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

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

array_count_values(array)

例如:

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

print_r(array_count_values($a));
Copy after login


输出:

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


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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template