How can I loop my array to total the score percentage based on his correct answer?

Viewed 98

I have this response

[0] => Array (
    [name] => Test
    [question_id] => 4
    [question_choice_id] => 14
    [choice_level] => 0
    )
[1] => Array (
    [name] => Test
    [question_id] => 5
    [question_choice_id] => 19
    [choice_level] => 0
    )
[2] => Array (
    [name] => Test
    [question_id] => 6
    [question_choice_id] => 24
    [choice_level] => 0
    )
[3] => Array (
    [name] => Test
    [question_id] => 7
    [question_choice_id] => 26
    [choice_level] => 0
    )
[4] => Array (
    [name] => Test
    [question_id] => 8
    [question_choice_id] => 29
    [choice_level] => 1
    )
[5] => Array (
    [name] => Test
    [question_id] => 9
    [question_choice_id] => 36
    [choice_level] => 0
    )
[6] => Array (
    [name] => Test
    [question_id] => 1
    [question_choice_id] => 2
    [choice_level] => 0
    )
[7] => Array (
    [name] => Test
    [question_id] => 2
    [question_choice_id] => 7
    [choice_level] => 0
    )
[8] => Array (
    [name] => Test
    [question_id] => 3
    [question_choice_id] => 9
    [choice_level] => 0
    )

I want to get the percentage of the user with the formula of

Score = the_right_answer / total_count_array * 100

The correct answer has a value of 1 in the choice_level columns

so for my example is, the formula should be

Score = 1/ 9 * 100

How can I get the total from this array?

Once I get the answer I just like to return them to my view.

  public function progress(){

    $category_id = Session::get('category_id');
    $user_set_id = Session::get('user_set_id');

    $score = Answer::get_user_score($user_set_id,$category_id);

      return view('pages.user.user_progress', [
        'name' => '',
        'score' => '',
      ]);

  }

Can anyone help me on how to do this properly? any help would be really appreciated.

3 Answers

Based on Score = total count_of_array / the_right_answer * 100:

  1. for total count_of_array could be calculated easily using count($answes)

  2. for calculating the_right_answer, you can use array_map() or manual loop:

     $total = count($answers);
     $correct = 0;
     foreach($answers as $answer){
       if($answer['choice_level'] == '1'){
         $correct++;
       }
     }
    

    the snippet above will give you $correct as total correct answer

  3. Now that you have the needed data, you can then do the calculation yourself. However, I would remind you that when the user doesn't have any correct answer, you will face a Division by zero warning. Keep that in mind

for each($arrayname['score'] as $item){
}

Since apparently choice_level can only take the values 0 or 1 you can use array_sum to get the number of correct answers. You will need to reduce the response array to just that field first, you can achive that with array_column. So all together:

$score = array_sum(array_column($answers, 'choice_level')) / count($answers) * 100;
Related