从平面数组创建唯一值及其计数的关联数组

发布于 2024-10-30 16:33:54 字数 207 浏览 1 评论 0原文

如何获得每个独特物品的计数?

示例:

$array = [
    "bye",
    "bye",
    "bye",
    "hello",
    "hello"
];
    

期望的结果:

['bye' => 3, 'hello' => 2] 

How can I get number of counts for each unique items?

Example:

$array = [
    "bye",
    "bye",
    "bye",
    "hello",
    "hello"
];
    

Desired result:

['bye' => 3, 'hello' => 2] 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

寒冷纷飞旳雪 2024-11-06 16:33:54

如果您想获取给定数组中指定列中唯一值的总数,作为简单整数(而不是另一个数组),请尝试如下简单操作:

$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")));

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")));
幼儿园老大 2024-11-06 16:33:54

您可以使用 array_count_values

print_r(array_count_values($array));

将返回:

Array
(
    [bye] => 3
    [hello] => 2
)

You can use array_count_values.

print_r(array_count_values($array));

will return :

Array
(
    [bye] => 3
    [hello] => 2
)
纵性 2024-11-06 16:33:54

您可以在您的数组将返回类似:

array(2){
    ["bye"]=> int(3)
    ["hello"]=> int(2)
}

示例用法:

$unique = array_count_values($my_array);

You can use array_count_values on your array which would return something like:

array(2){
    ["bye"]=> int(3)
    ["hello"]=> int(2)
}

Example Usage:

$unique = array_count_values($my_array);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文