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

yoh*_*man 21 php arrays loops

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

$unique_items=array_unique($items); // gives me 4,2
Run Code Online (Sandbox Code Playgroud)

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

Yos*_*shi 45

请参阅:array_count_values

喜欢:

$occurences = array_count_values($items);
print_r($occurences);
Run Code Online (Sandbox Code Playgroud)

输出:

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

用法:

echo $occurences[4]; // outputs 3
Run Code Online (Sandbox Code Playgroud)