0

I've got a csv file with column headers. What I'm looking for is, that how can I take out the number from column no. 9 (currency amount) from only those rows, which contain "XYZxxxx" code in the 2nd column and add them up with only the same kind of currency specified in col no. 10?

My approach until now is:

  1. Parse the content of csv into php array.
  2. Explode the content into different rows.
  3. Check for rows containing "XYZxxxx".

Then I cannot figure out, how to take the amount of currency and the type of currency out from these and sum the up with the same type.

I'm thinking that I can look separately for "EUR", "GBP" & "USD" values and group the rows into different variables based on the results, but is it a correct approach or am I overthinking it?

1
  • 1
    Show code please. Commented Dec 10, 2016 at 11:47

1 Answer 1

1

Some simple solution:

$array = [
    [10, 'DOLLAR'],
    [20, 'DOLLAR'],
    [25, 'EURO'],
    [20, 'DOLLAR'],
    [25, 'EURO'],
];

$sums = [];
foreach ($array as $item) {
    if (empty($sums[$item[1]])) {
        $sums[$item[1]] = $item[0];
    } else {
        $sums[$item[1]] += $item[0];
    }
}

echo'<pre>',print_r($sums),'</pre>';
//Array
//(
//    [DOLLAR] => 50
//    [EURO] => 50
//)

Extended example:

$array = [
    [10, 'DOLLAR', 'XYZ1010'],
    [20, 'DOLLAR', 'ABC'],
    [25, 'EURO', 'XYZ1010'],
    [20, 'DOLLAR', 'XYZ1010'],
    [25, 'EURO', 'ABC'],
];

$sums = [];
foreach ($array as $item) {
    if (strpos($item[2], 'XYZ') !== false) {
        if (empty($sums[$item[1]])) {
            $sums[$item[1]] = $item[0];
        } else {
            $sums[$item[1]] += $item[0];
        }
    }
}

echo'<pre>',print_r($sums),'</pre>';
//Array
//(
//    [DOLLAR] => 30
//    [EURO] => 25
//)

Do not create a lot of variables with names like $dol, $gbp etc. Use one single array with keys.

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

9 Comments

My problem is the logic to get until I have the filtered array to add up. I imagine it like: eur=0, gbp=0, usd=0, "foreach row where column no.2 has the value "XYZxxx": if col no. 10 = EUR then eur = eur+col no.9 value"; elseif col no. 10 = GBP gbp = gbp+col no9 value; else usd = usd + col no.9 value.
And where's the problem exactly?
That I don't know how can I specify these columns of the csv file, I mean how to tell php which one is which column of the current row.
I still don't understand. You know what $array[index] syntax means? Maybe you add some code to your question?
I advise you to print your multidminsional array and see what you have there. And what keys you can use to get values from it.
|

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.