基于数组值的速率数组

时间:2013-01-24 15:32:48

标签: php arrays sorting

occurrence of A----5 times
occurrence of B----7 times
occurrence of C----6 times
($total['A']=5;
 $total['B']=7;
 $total['C']=6;)

我需要根据它们的出现率对每个进行评分,如下所示,

$rating['A']=3;
$rating['B']=1;//most occurrence will get rate 1.
$rating['C']=2;

2 个答案:

答案 0 :(得分:2)

asort(&$total);
$rating = 1;
foreach (array_reverse($total) as $key => $val)
    $total[$key] = $rating++;

答案 1 :(得分:0)

您还可以尝试使用数组函数,例如首先对值进行排序并获取已排序数组的键,然后使用提取的键作为值创建另一个数组。现在你获得了与他们的排名相同的数组,除了你排在第0位,因为数组以索引0开头。

可能你可以使用'0'来填充额外的值,然后最终删除它。

像这样,

$total['A']=5;
$total['B']=7;
$total['C']=6;

$total[0]=0;
asort($total);
$total = array_slice(array_flip(array_keys($total)),1);

或者,如果您不想填充额外的值,可以这样尝试。使用键和排序数组的计数创建一个数组。

asort($total);
$total = array_combine(array_keys($total),range(1, count($total)));

这可能是一种快速简便的方法。希望这会有所帮助。

相关问题