php将新字段添加到数组并将其显示
问题描述:
下面给出的代码是读取csv文件并将值检索到字段$ time,$ sip,$ dip和$ data。我需要检索,php将新字段添加到数组并将其显示
- first_time_stamp
- SIP/DIP
- sum_of_all_values_at_SIP
- sum_of_all_values_at_DIP
下面的代码是总和起来。但我找不到分开的啜饮。我需要分开寻找啜饮和浸泡。也是第一次的时间戳。
2014-10-31 23:34:06,10.101.11.122,54.252.136.82,2047
2014-10-31 23:34:08,31.13.70.81,10.101.84.6,49580
2014-10-31 23:34:15,10.101.11.122,54.252.136.82,20
2014-10-31 23:34:09,54.252.136.82,10.101.11.122,20
2014-10-31 23:34:12,10.101.11.13,10.101.11.122,20
如:
$lines =file('/ghgj.csv');
$records=array();
$i=1;
foreach($lines as $line)
{
list($time,$sip,$dip,$data)= explode(',',$line);
if(substr($sip, 0, 3)=="10.")
{
if(key_exists($sip, $records))
{
$records[$sip] += $data;
}
else
{
$records[$sip] = $data;
}
}
else if(substr($dip, 0, 3)=="10.")
{
if(key_exists($dip, $records))
{
$records[$dip] += $data;
}
else
{
$records[$dip] = $data;
}
}
else
{
continue;
}
$i++;
}
}
CSV文件的例子在下面给出我的代码输出:
10.101.11.122(sip or dip),2087
10.101.84.6,49580
10.101.11.13,20
如:输出应该是这样的:
2014-10-31 23:34:06(timestamp),10.101.11.122(common sip or dip),2067(sum of sip),20(sum of dip)
2014-10-31 23:34:08,10.101.84.6,0,49580
2014-10-31 23:34:06,10.101.11.13,20,0
谢谢!
答
看看这是否适合你。正如@jerdiggity所写的,你也可以使用fgetcsv(),但在你的情况下(没有引号,特别是CSV数据中没有引用逗号或换行符),这是没有必要的。
$lines =file('/ghgj.csv');
$records=array();
$i=1;
foreach($lines as $line)
{
list($time,$sip,$dip,$data)= explode(',',$line);
if(substr($sip, 0, 3)=="10.")
{
if (!key_exists($sip, $records))
{
$records[$sip] = array(
'timestamp' => $time,
'sip' => 0,
'dip' => 0
);
}
$records[$sip]['sip'] += $data;
}
else if(substr($dip, 0, 3)=="10.")
{
if (!key_exists($dip, $records))
{
$records[$dip] = array(
'timestamp' => $time,
'sip' => 0,
'dip' => 0
);
}
$records[$dip]['dip'] += $data;
}
else
{
continue;
}
$i++;
}
你看过[fgetcsv()](http://php.net/manual/en/function.fgetcsv.php)吗?可能对你的情况有所帮助......只是一个想法。 – jerdiggity 2014-11-09 07:57:22