1

I have two different arrays:

$dep = Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 3 )

and

$q1_a = Array ( [0] => 4 [1] => 4 [2] => 4 [3] => 2 [4] => 4 [5] => 2 )

I put it in one array:

$arr = array($dep, $q1_a);

And then I got:

Array ( 
[0] => Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 3 ) 
[1] => Array ( [0] => 4 [1] => 4 [2] => 4 [3] => 2 [4] => 4 [5] => 2 ) )

How can I summarize variables of second array where it matches specific number in first. So I need to find sum of numbers where first array has 1,2 and 3. And to get 3 different numbers.

so first number will be:

[0] => 1 [1] => 1 [2] => 1
[0] => 4 [1] => 4 [2] => 4 
4+4+4=12

second:

[3] => 2
[3] => 2
2

third:

[4] => 3 [5] => 3
[4] => 4 [5] => 2
4+2=6

How can I do that?

2 Answers 2

2

Try this, live demo.

<?php
$dep = [1,1,1,2,3,3];
$q1_a = [4,4,4,2,4,2];

$flag = current($dep);
$result = [0];
foreach($dep as $k => $v){
  if($flag == $v) {
    $val = end($result);
    $result[key($result)]= $val + $q1_a[$k];
  }
  else
    $result[] = $q1_a[$k];
  $flag = $v;
}
print_r($result);
Sign up to request clarification or add additional context in comments.

Comments

0
$cur_index = null;  
$result = [];
$j = 0;
for ( $i = 0; $i < length($dep); $i++) {  
  if ($cur_index == null){ 
    $result[$j] = $q1_a[$i];
    $cur_index = $dep[i];
  }
  else if ($cur_index == $dep[$i]) {
    $result[$j] += $q1_a[$i]
  }
  else {
    $cur_index = $dep[i];
    $result[++$j] += $q1_a[$i];
  }   
} 

Hope this work and this syntax may not correct.

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.