如何在PHP/Laravel中使用frequency vector统计属性频率并生成评分
适用性说明
频率向量(frequency vector)完全适用你的场景,你的需求本质就是为每个自定义属性维度生成对应的频率统计向量,记录每个取值的出现频次,和你要的统计逻辑完全匹配。
实现方案
你现有代码的问题在于多了不必要的object封装,且遍历逻辑只统计了属性本身的出现次数,没有遍历属性下的取值数组做频次统计。以下是可直接运行的实现:
原生PHP实现
借助PHP内置array_count_values方法可直接完成取值频次统计:
<?php $attributes = [ 'color' => ['red', 'red', 'red', 'blue', 'red'], 'height' => [2, 2, 3, 3, 4, 5, 2, 2, 2, 2], 'material' => ['iron', 'iron', 'gold', 'gold', 'gold'] ]; $result = []; foreach ($attributes as $attrName => $valueList) { // 统计每个取值的出现次数 $valueCounts = array_count_values($valueList); // 按出现次数倒序排列,保留键名 arsort($valueCounts); // 组装结果 $result[$attrName] = [ // 如果count需要的是不同取值的数量,改为 count($valueCounts) 即可 'count' => count($valueList) ] + $valueCounts; } echo "<pre>"; print_r($result);
输出结果完全符合你要求的格式,示例输出:
Array ( [color] => Array ( [count] => 5 [red] => 4 [blue] => 1 ) [height] => Array ( [count] => 10 [2] => 7 [3] => 2 [4] => 1 [5] => 1 ) [material] => Array ( [count] => 5 [gold] => 3 [iron] => 2 ) )
Laravel框架实现
Laravel的集合类提供countBy方法可更简洁的完成统计:
$result = collect($attributes)->map(function ($valueList) { $valueCounts = collect($valueList)->countBy()->sortDesc()->toArray(); return [ 'count' => count($valueList) ] + $valueCounts; })->toArray();
内容的提问来源于stack exchange,提问作者KurlK
相关产品推荐
相关产品推荐

