我有一个阵列说:
$array = array(1, 5, 2, 3, 3, 4, 5, 1)
我想转换此数组并将值作为键,将其频率作为值 输出应该是:
$array = array (
"1" => 2,
"2" => 1,
"3" => 2,
"4" => 1,
"5" => 2
)
我知道如何在python中执行此操作。但我必须用PHP来做。我已经在python中使用以下代码实现了这个: python代码:
d = {}
for j in tweets: // tweet is a array of integers as given above $array
d[j] = d.get(j, 0) + 1 // This will make a dictionary with the values in the array as key and its frequency as value of the dictionary .. Get() dynamically increase the value
请帮忙。
答案 0 :(得分:2)
$newArray = array_count_values( $array );
在此处查看:[{3}}
要按其键对其进行排序,请使用ksort
:
ksort( $newArray );
在此处查看:[{3}}