Jump to content

Create array from csv file.


ISAB

Recommended Posts

Hi everyone. 

 

I have a csv file, im trying to read and output the number of unique row according to second column. 

 

csv file : 

2013-03-25 00:00:06,"00:0E:6D:3F:D5:76","-68","5374468","B"

2013-03-25 00:00:07,"04:A8:2A:18:8A:04","-66","5898756","B"

2013-03-25 00:00:08,"00:0E:6D:3F:D5:76","-68","5374468","B"

 

so the output of the csv file should be 2.

 

 

I appreciate any help thanks :)

Link to comment
https://forums.phpfreaks.com/topic/277052-create-array-from-csv-file/
Share on other sites

This might work:

$file = file_get_contents('file.csv');
$lines = explode("\n", $file);
$buckets = array();
foreach ($lines as $line)
{
	$items = explode(',', $line);
	$c2 = $items[1];
	if (!isset($buckets[$c2]))
		$buckets[$c2] = 1;
	else
		$buckets[$c2]++;
}
krsort($buckets);

echo key($buckets);

It will break if you get commas inside the quotes, but assuming that data is consistent, it shouldn't matter.

or use array_count_value()

$f = fopen('test.csv','r');
while ($line=fgetcsv($f, 1024)) {
    $arr[] = $line[1];
}
$counts = array_count_values($arr);
asort($counts);    // sort least occuring to top
echo key($counts);
fclose($f);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.