2

ループして特定の列の値を読み取り、各値が表示される頻度を数えようとしている .csv ファイルがいくつかあります。たとえば、ファイルの 1 つの 3 番目の列を と呼びますが$col[2]、次のようになります。

HEADER
foo
bar
bar
bar
foo

このコードを使用して、両方の回数をカウントし、ファイルfooに表示できます。bar

$file = ('Path/To/Random/File.txt');

$fh = fopen($file, 'rb');

$tag = array();
while($col = fgetcsv($fh)) {
    $tag[$col[2]]++;
}

print_r($tag);

Result:

5

ただし、このコードは のすべての値のカウントを返しますcol[2]。どのカウントがどの値に属しているかにのみ分割してfoo、値の数が必要であることを指定するにはどうすればよいですか? barたとえば、結果は次のようになります。

echo $foo_count;
echo $bar_count;

Result:

2
3
4

1 に答える 1

2

I would do:

$file = ('Path/To/Random/File.txt');

$fh = fopen($file, 'rb');

$tag = array();
while($col = fgetcsv($fh)) {

if (isset($tag[$col[2]])) {
   $tag[$col[2]]++;
}
else {
   $tag[$col[2]] = 1;
}

be sure $col[2] actually contains the value you want to measure/iterate

once that you should have an array like, use print_r to check

'foo' => 2,
'bar' => 3
于 2012-12-27T18:30:32.210 に答える