1

I have a total black out. I have one array with n elements which has the results of a team, such as:

array(teamid, wins, losses, draws, goals);

array(1, 2, 3, 4, 5);
array(2, 2, 3, 4, 5);
array(1, 1, 2, 2, 6);
array(2, 2, 3, 4, 5);

I want to iterate through this array and sum up the values for each team-id in a second array. Such as:

$results = getResults();
$final = array();

foreach ($results as $result) {
foreach ($results as $res) {
if ($res['team_id'] == $result['team_id']) {
...
}
}
}

foreach ($final as $finalresult) {
...print result
}

In the end I want an array with e.g. in this example 2 values with 2 different team ids, each values summed up, but I have a blackout at the moment.

Does anybody have a solution?

Thanks.

1
  • your data example and the code don't match; this makes it very hard to answer the question Commented Aug 13, 2012 at 20:07

2 Answers 2

2

Your code is confusing, but I guess it will give a hint:

$results = getResults();
$final = array();

foreach ($results as $result) {
    if(!isset($final[$result['team_id']])) {
        $final[$result['team_id']] = $result['wins'];
    } else {
        $final[$result['team_id']] += $result['wins'];
    }
}

foreach($final as $key=>$value) {
    echo $key . ' ' . $value . '</br>';
}
Sign up to request clarification or add additional context in comments.

Comments

2

You're running the loops nested, which means you're actually summing n^2 records. Assuming the array keys are the same between both arrays, then you'd only need a single loop:

$arr1 = array(...);
$arr2 = array(...);
$sum = 0;

foreach($arr1 as $key => $value) {
    $sum += $arr1[$key] + $arr2[$key];
}

If the keys aren't the same,t hen you'll have to figure out to match up the members of the two arrays.

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.