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

Php 从给定数据中查找最常见的值,php,csv,Php,Csv,我有一些数据看起来像这样 +----------+----------+----------+ | Column 1 | Column 2 | Column 3 | +----------+----------+----------+ | Red | Blue | Green | | Yellow | Blue | Pink | | Black | Grey | Blue | +--------------------------

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

+----------+----------+----------+
| Column 1 | Column 2 | Column 3 |
+----------+----------+----------+
|   Red    |   Blue   |   Green  |
|  Yellow  |   Blue   |   Pink   |
|  Black   |   Grey   |   Blue   |
+--------------------------------+
我需要仔细查看这些数据,找出3种最常见的颜色

原始数据是CSV格式的,可能还有数千行。()


最好的方法是什么?

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

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


并对每种颜色进行计数。

如果可以管理可能的颜色数量,只需使用关联数组即可:

$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.

如果您使用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

中的第一个元素,即每列或所有列中最常见的三种颜色??所有列。假设每个用户都会告诉我他们最喜欢的3种颜色,然后我想选择3种最流行的颜色。