计算数组(PHP)中唯一项的数量的聪明方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5553981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is a clever way to count number of unique items in array (PHP)?
提问by Cory
Possible Duplicate:
Unique entries in an array
可能重复:
数组中的唯一条目
Let assume the array is sorted, how can I get number of counts for each unique items
假设数组已排序,我如何获得每个唯一项目的计数
Example:
例子:
$array = array ("bye", "bye", "bye", "hello", "hello");
Output:
输出:
bye = 3
hello = 2
回答by Stefan Gehrig
If you want to get the total count of unique values in a specified column within a given array, as a simple integer (rather than another array) try something simple like this:
如果您想获取给定数组中指定列中唯一值的总数,作为一个简单的整数(而不是另一个数组),请尝试以下简单操作:
$uniqueCount = count(array_unique(array_column($data, 'column_name')));
// (where $data is your original array, and column_name is the column you want to cycle through to find the total unique values in whole array.)
var_dump(array_count_values(array("bye", "bye", "bye", "hello", "hello")));
回答by krtek
You can use array_count_values.
您可以使用array_count_values。
print_r(array_count_values($array));
will return :
将返回 :
Array
(
[bye] => 3
[hello] => 2
)
回答by RobertPitt
You can use array_count_values
on your array which would return something like:
你可以array_count_values
在你的数组上使用它会返回类似的东西:
array(2){
["bye"]=> int(3)
["hello"]=> int(2)
}
Example Usage:
示例用法:
$unique = array_count_values($my_array);