php将新字段添加到数组并显示它

时间:2014-11-09 06:43:59

标签: php arrays csv multidimensional-array

下面给出的代码是读取csv文件并将值检索到$ time,$ sip,$ dip和$ data字段。我需要检索,

  1. first_time_stamp
  2. SIP / DIP
  3. sum_of_all_values_at_SIP
  4. sum_of_all_values_at_DIP
  5. 下面的代码是总和。但我找不到分开的啜饮和蘸酱。我需要分别找到啜饮和蘸酱。也是第一个时间戳。

        $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文件的示例如下:

    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
    

    例如:输出我的代码:

    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
    

    谢谢!

1 个答案:

答案 0 :(得分:1)

看看这是否适合您。正如@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++;  
}