1

I have a csv file and it has four fields which are time,sip,dip and data.

I need to find all sips which starts with "10." and if sips are same add all data field and display the value with sip.

I have tried the code below. But how can I search the array to check whether sips are same, if they are same add all data field.

$lines =file('/files/cjsv.csv');
$records=array();
foreach($lines as $data)
{
  list($time,$sip,$dip,$data)= explode(',',$data);
  if(substr($sip, 0, 3 )=="10.")
  {
     echo $sip."=".$data."<br/>";
     $records[$sip]=$data;
  }

}
var_dump($records);

Example of a csv file:

2014-10-31 23:34:24,17.172.208.49,10.101.224.170,500
2014-10-31 23:34:16,178.206.115.117,10.101.224.170,400
2014-10-31 23:34:23,10.101.16.218,17.167.138.38,200
2014-10-31 23:34:23,10.101.16.218,17.167.138.38,100
2014-10-31 23:34:24,54.249.250.113,10.101.13.22,80
2014-10-31 23:34:24,17.167.140.109,10.101.1.1,80
2014-10-31 23:34:24,134.170.188.84,10.101.1.1,80
2014-10-31 23:34:23,10.101.16.219,17.167.138.38,50

Expected output is:

10.101.16.218=300(200+100)

10.101.16.219=50

3
  • 1
    actually which part is not working...?? I know your answer... Commented Nov 7, 2014 at 13:01
  • 1
    Could you post a result? So the output you are expecting.. Commented Nov 7, 2014 at 13:01
  • 1
    I have updated the expected output. Commented Nov 7, 2014 at 13:07

2 Answers 2

1

I tested this code and it's outputting the result that you want...

$lines =file('/files/cjsv.csv');
$records=array();
foreach($lines as $data)
{
  list($time,$sip,$dip,$data)= explode(',',$data);
  if(substr($sip, 0, 3 )=="10.")
  {
     //echo $sip."=".$data."<br/>";
     $records[$sip] += $data;          // changed this
  }
}
var_dump($records);

Output:

array(2) {
  ["10.101.16.218"]=>
  int(300)
  ["10.101.16.219"]=>
  int(50)
}

I changed only one command from your solution "$records[$sip]=$data;" to "$records[$sip] += $data;"... "=" will replace the previous value you recorded where "+=" will increment the value, that you want...

feel free to ask if you have any further questions...

Sign up to request clarification or add additional context in comments.

Comments

1

Something like:

if(key_exists($sip, $records){
    $records[$sip] += $data;
} else {
    $records[$sip] = $data;
}

3 Comments

maybe you were referring to array_key_exists, or just use isset
key_exists() is simply an alias of array_key_exists()
actually whats unclear is that whether the OP need to need another set of array inside the container to just add sum those last digits

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.