php 如何计算数组中相同的值并将其存储到变量中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6408095/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:17:34  来源:igfitidea点击:

How do i count same values in an array and store it to a variable?

phparraysloops

提问by yohdaman

$items = explode(',',$product); // values is 4,2,4,2,2,4

$unique_items=array_unique($items); // gives me 4,2

What code should be next to give me 4 = 3 , 2 = 3 and store the number of values to a variable?

接下来应该是什么代码给我 4 = 3 , 2 = 3 并将值的数量存储到变量?

回答by Yoshi

see: array_count_values

请参阅:array_count_values

Like:

喜欢:

$occurences = array_count_values($items);
print_r($occurences);

Output:

输出:

Array
(
    [4] => 3
    [2] => 3
)

Usage:

用法:

echo $occurences[4]; // outputs 3

回答by duri

You're probably looking for array_count_values() function.

您可能正在寻找 array_count_values() 函数。