2

I want to take an input file (data.txt), where 1st column is a name, and 2nd is a 2-decimal number ... process the whole file no matter how many lines it has ... and get an output with 3 columns ... 1) number of iterations for each name ... 2) name ... 3) sum of values (4,49 + 1,22 + 9,15)

input sample:
name 111    4,49
name 111    1,22
name 111    9,15
name 222    1,99
name 222    1,22
name 333    4,49
name 333    25,80
name 333    11,11
name 333    4,49
name 333    4,49
name 333    25,80
name 333    4,49
name 444    14,95
name 444    9,15
etc. ...
(hundreds of lines)


output sample:
3   name 111    14,86
2   name 222    3,21
7   name 333    80,67
etc. ...
(all data like this)

My idea was to create a two-dimensional array first ... then take 1st name, compare with the next, if they match -> add up the values and go on ... if they don't match -> new line in output

I was able to get the array, but then got lost in the "loop" part comparing + calculating array items.

$lines = file('data.txt'); // Reads an entire file into an array

$two_array = array(); // creates two-dimensional array
foreach($lines AS $row){
    $two_array[] = explode("\t", $row); // Explode each row by TAB to each row of two_array
}

print_r($two_array);
3

Use the first part of the explode() result as a key in the second array and check if it exists. If it does, add the current value to that element, if not, initialize it with it.

$lines = file('data.txt'); // Reads an entire file into an array

$two_array = array(); // creates two-dimensional array
foreach($lines AS $row){
    list($key, $value) = explode("\t", $row); // Explode each row by TAB to each row of two_array
    if (isset($two_array[$key])) {
        // already exists, add it to the existing value
        $two_array[$key]['sum'] += $value;
        $two_array[$key]['count'] += 1;
    } else {
        // initialize
        $two_array[$key]['sum'] = $value;
        $two_array[$key]['count'] = 1;
    }
}

foreach ($two_array as $key => $value) {
    printf(
        '%s -- %s -- %s', // whatever format you need
        $value['count'],
        $key,
        $value['sum']
    );
}

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.