[英]Group by a column from csv and sum the values from another (PHP)
I have a csv like this: 我有这样的csv:
25/07/2016 3
25/07/2016 4
26/07/2016 4
26/07/2016 1
And the output that i expect, it have to be like this 我期望的输出必须像这样
25/07/2016 7
26/07/2016 5
I want to do this only using PHP. 我只想使用PHP来做到这一点。 I have to mention that i am not using mysql and i don't want to. 我不得不提到,我没有使用mysql,也不想使用。 Is there a solution to do that? 有解决方案吗?
Try something like this. 尝试这样的事情。 This is just an edited version from this similar post . 这只是该类似文章的编辑版本。
$my_file = fopen('file.csv', 'rb');
$my_array = array();
while($row = fgetcsv($my_file)) {
$my_array[$row[0]] += $row[1];
}
"25/07/2016","3"
"25/07/2016","4"
"26/07/2016","4"
"26/07/2016","1"
For eg Let's say you have CSV file that contains data as above. 例如,假设您的CSV文件包含上述数据。
$arr = array();
$handle = fopen("example.csv", "r");
while(!feof($handle))
{
$arrOfCSVLine = fgetcsv($handle);
$date = $arrOfCSVLine[0];
$no = $arrOfCSVLine[1];
if(!array_key_exists($data,$arr))
{
$arr[$date] = $no;
}
else
{
$arr[$date] += $no;
}
}
echo '<pre>';
print_r($arr);
check this code.. 检查此代码。
$finalOutput = array();
$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
if(isset($finalOutput[$line[0]])){
$finalOutput[$line[0]] = $line[1] + $finalOutput[$line[0]];
} else {
$finalOutput[$line[0]] = $line[1];
}
}
print_r($finalOutput);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.