Home > other >  Comparing two arrays and get the sum of all key=>value where key is in another array
Comparing two arrays and get the sum of all key=>value where key is in another array

Time:12-27

I have the array array1

   array:5 [
  0 => array:1 [
    2 => array:2 [
      "type" => 1
      "score" => 10
    ]
  ]
  1 => array:1 [
    2 => array:2 [
      "type" => 2
      "score" => 5
    ]
  ]
  2 => array:1 [
    2 => array:2 [
      "type" => 3
      "score" => 4
    ]
  ]
  3 => array:1 [
    2 => array:2 [
      "type" => 4
      "score" => 60
    ]
  ]
  4 => array:1 [
    1 => array:2 [
      "type" => 1
      "score" => 5
    ]
  ]
]

I have the second array2 which is one dimensional

array:2 [  0 => 2, 1 => 1]

I want to get the sum of all the score values in array1 where the array1.key = array2.val which will result to:

array:5 [
  0 => array:1 [
    2 => array:2 [
      "score" => 79
    ]
  1 => array:2 [
    1 => array:2 [
      "score" => 5
     ]
    ]
]

This is what i've tried

// getResult (result,remarks,psychomotor) based on periodid
    $result = Result::join('subject__class_groups', 'results.subjectid', 'subject__class_groups.id')
    ->join('term__session__years', 'results.academic_periodid', 'term__session__years.id')
    ->join('result_types', 'results.restult_typeid', 'result_types.id')
    ->join('terms', 'term__session__years.termid', 'terms.id')
    ->join('academic_sessions', 'term__session__years.sessionid', 'academic_sessions.id')
    ->join('academic_years', 'term__session__years.yearid', 'academic_years.id')
    ->join('subjects', 'subject__class_groups.subjectid', 'subjects.id')
    ->join('class_groups', 'subject__class_groups.classgroupid', 'class_groups.id')
    ->where('results.studentid', $studentid)
    ->where('results.academic_periodid', $periodid)->get();

    $allSubjects = [2,1];
    $subs = [];
    foreach($result as $res){
        // solve for everysubjectid
        $subject = array_push($allSubjects, $res->subjectid);
        $returnValue = array_unique($allSubjects);

            $getScores = array_push($subs, [$res->subjectid=>[
                    'type'=>$res->restult_typeid,
                    'score'=>$res->score_obtained,
            ]]);


    }
    $check = array_intersect_key($returnValue, $subs);

        dd($check);

I'm stuck here cos i don't know what exactly to do

so i'll appreciate a bit of help guys... compliments of the seasons thank you in anticipation

CodePudding user response:

try this:

foreach( $array1 as $array1x ){
    $key=key($array1x);
    if( in_array($key, $array2) ){
        $this_score = $array1x[$key]['score'];
        $cum_score = isset($newarray[$key]['score']) ? $newarray[$key]['score'] : 0;
        $newarray[$key]['score'] = $cum_score   $this_score;
    }
}
print_r($newarray);

DEMO: https://3v4l.org/iKU8j

  • Related