什么是计算数组(PHP)中唯一项数的巧妙方法?

Cor*_*ory 12 php

可能重复:
数组中的唯一条目

假设数组已排序,我如何获得每个唯一项的计数

例:

  $array = array ("bye", "bye", "bye", "hello", "hello");
Run Code Online (Sandbox Code Playgroud)

输出:

    bye   = 3
    hello = 2 
Run Code Online (Sandbox Code Playgroud)

Ste*_*rig 25

如果要获取给定数组中指定列中唯一值的总数,则作为一个简单整数(而不是另一个数组)尝试这样简单的事情:

$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")));
Run Code Online (Sandbox Code Playgroud)


krt*_*tek 21

您可以使用array_count_values.

print_r(array_count_values($array));
Run Code Online (Sandbox Code Playgroud)

将返回 :

Array
(
    [bye] => 3
    [hello] => 2
)
Run Code Online (Sandbox Code Playgroud)