2

I can't get my head around this.
I have a csv-file containing companynames and a certain value.

I run a script that get's the companyname and value from the csv.
A company can contain multiple values. Here's what it looks like

[company1][123]
[company1][65456]
[company1][435]
[company1][234235]
[company2][65464]
[company2][53543]

What I want to do is get every value from every separate company and calculate the sum of all values from that specific company.

So I tried this:

foreach($data as $companies){
    $company = $companies['name'];
    $value = $companies['value'];
    if ($company == 'company1'){
        echo $value;
    }
} 

$data is the array with values from the csv

For testing purposes I have manually written a companies name in the if statement but this should be dynamically loaded from the $data-array.

After this it should calculate the sum of all values.

How can I accomplish this?

2
  • you need all companies sum or sum of each company?? Commented Jun 30, 2017 at 7:20
  • No the sum of the values belong to that company Commented Jun 30, 2017 at 7:24

2 Answers 2

3

You can use the following solution:

$arr_sum = [];

foreach ($data as $companies) {
    $company = $companies['name'];
    $value = $companies['value'];

   if (!isset($arr_sum[$company])) {
       $arr_sum[$company] = 0;
   }

   $arr_sum[$company] += $value;
}

demo: http://ideone.com/KXGCOd

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

1 Comment

Dude... Like a charm. Thank you!
1

if I understand well your issue, this should work.

$data = [
['name' => 'company1', 'value' => 123],
['name' => 'company1', 'value' => 65456],
['name' => 'company1', 'value' => 435],
['name' => 'company1', 'value' => 234235],
['name' => 'company2', 'value' => 65464],
['name' => 'company2', 'value' => 53543]
];
$result = 0;
foreach($data as $companies)
{
    $company = $companies['name'];
    $value = $companies['value'];
    if ($company == 'company1')
    {
        $result += $value;
    }
} 
echo $result;

HOWEVER! PHP is not very powerful when it comes to calculations, especially when embedded in a loop. If your companies has couple of different values each and you have couple of companies too, then fine. But if your file contains thousands of companies with many values, then your script will be very limited (think to increase/deactivate server time out). I would suggest to use python for your specific case, it would be much faster, easier and more important: it will scale :)

Comments

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.