Php 我如何循环数组,根据他的正确答案计算总分百分比?

Php 我如何循环数组,根据他的正确答案计算总分百分比?,php,arrays,laravel,Php,Arrays,Laravel,我有这样的回答 [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 [choi

我有这样的回答

[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
    )

我想用公式得到用户的百分比

Score=正确答案/总计数数组*100

正确答案在
choice\u level
列中的值为1

我的例子是,公式应该是

Score=1/9*100

如何从这个数组中获取总数

一旦我得到答案,我只想让他们回到我的观点

  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' => '',
      ]);

  }

有谁能帮我正确地做这件事吗?任何帮助都将不胜感激。

基于
得分=数组总计数/正确答案*100

for each($arrayname['score'] as $item){
}
  • 使用
    count($answes)

  • 要计算
    正确答案
    ,可以使用
    数组映射()
    或手动循环:

     $total = count($answers);
     $correct = 0;
     foreach($answers as $answer){
       if($answer['choice_level'] == '1'){
         $correct++;
       }
     }
    
    上面的代码片段将为您提供总正确答案
    $correct


  • 现在您已经有了所需的数据,您可以自己进行计算了。但是,我要提醒您,当用户没有任何正确答案时,您将面临一个
    除零
    警告。请记住,因为显然
    choice\u level
    只能取
    0
    1
    的值,您可以使用这些值来获得正确答案的数量。您首先需要将响应数组减少到该字段,您可以使用。因此,总而言之:

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

    这是一种奇怪的计算分数百分比的方法,应该是
    正确答案/数组计数*100
    ?@catcon哦,对不起,先生,我已经更新了我的问题,谢谢你的更正,先生,我被弄糊涂了。是的,谢谢你,先生,我的公式不正确,应该是``正确答案/数组总数*100。非常感谢您,先生。@ariefbayu您能帮我解决这个问题吗。。。