0

i have two arrays like

    $a1                $b1
0 : A                  10
1:  B                  10
2:  A                  15
3:  A                  20
4: B                   05
5: c                   25

now i want to calculate them in same way then result is A=45, B=15 and C=25

1
  • 8
    So what have you tried so far? Commented Aug 23, 2012 at 13:31

2 Answers 2

1
$calc = array_fill_keys($a1,0);
foreach($a1 as $i => $key) {
  $calc[$key] += $b1[$i];
}

$calc is array of calculated values:

[A] => 45,
[B] => 15
etc.
Sign up to request clarification or add additional context in comments.

3 Comments

Don't cheat with @, use $calc = array_fill_keys($a1,0) to remove the warnings
can you tell me one more thing that how can i print $calc values in different html cells like A 45
echo "<table>"; foreach($calc as $key=>$value) { echo "<tr><td>{$key}</td><td>{$value}</td></tr>"; } echo "</table>";
0

I know it's already been answered and accepted, and the accepted answer is a lot simpler and more efficient; but purely because I was tempted to try a rather different approach:

$a1 = array('A', 'B', 'A', 'A', 'B', 'c');
$b1 = array('10','10','15','20','05','25');

$sumArray = array();
foreach(array_unique($a1) as $key) {
    $arrayElements = array_filter(
                         $a1,
                         function($value) use ($key) {
                             return $value == $key;
                         }
                     );
    $sumArray[$key] = array_sum(
                          array_intersect_key(
                              $b1,
                              array_fill_keys(
                                  array_keys($arrayElements),
                                  NULL
                              )
                          )
                      );
}

var_dump($sumArray);

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.