从给定数据中查找最常见的值

时间:2010-04-01 21:57:04

标签: php csv

我有一些看起来像这样的数据......

+----------+----------+----------+
| Column 1 | Column 2 | Column 3 |
+----------+----------+----------+
|   Red    |   Blue   |   Green  |
|  Yellow  |   Blue   |   Pink   |
|  Black   |   Grey   |   Blue   |
+--------------------------------+

我需要查看这些数据并找到3种最常见的颜色。

原始数据采用CSV格式,可能还有数千行。 (link

这样做的最佳方式是什么?

4 个答案:

答案 0 :(得分:7)

没有魔法......一次一行,一次一列。

计算每种颜色。

答案 1 :(得分:2)

循环遍历所有值,同时保持数组中每一个的计数(word => count)。完成后,找到值最高的键。

答案 2 :(得分:2)

如果可管理的颜色数量很多,只需使用关联数组:

$histo = array();

//foreach cell
  $color = ??; //however you're getting a cell's value
  if(!isset($histo[$color]))
    $histo[$color] = 1;
  else
    $histo[$color]++;
//end loop

//reverse sort by value
$histo = arsort($histo);

//now the first three colors in $histo are the most common ones.

答案 3 :(得分:1)

如果您正在使用PHP而不是数据库进行处理,并且该文件包含纯颜色名称,我会选择以下内容:

$colors = array();

$fh = fopen('data.txt');
while($row = fgetcsv($fh)) { // omitting length/delimiter arguments
    foreach($row as $field) {
        $colors[$field]++;
    }
}
fclose($fh);

$colors = arsort($colors); // sort in decescending order

之后,前3种颜色将成为$colors中的第一个元素。

相关问题