Foreach循环基于更高的数字增加总数

时间:2017-09-05 09:43:21

标签: php arrays

我正在计算得分并且只想收集更高的分数。这来自Laravel系列。

我目前有4个分数。

  

5,4,5,4

其中两个得分来自同一个video_id。所以我想只增加我的总数,如果迭代中的下一个分数高于前一个数字。

我的数组如下所示:

array:4 [
  0 => array:9 [
    "hazard_score_id" => 2
    "user_id" => 17019
    "hazard_score" => 5
    "hazard_video_name" => "Clip 1"
    "hazard_video_id" => 111860212
    "hazard_video_section" => "theory"
    "created_at" => "2017-09-05 08:36:45"
    "updated_at" => "2017-09-05 08:36:45"
    "deleted_at" => null
  ]
  1 => array:9 [
    "hazard_score_id" => 3
    "user_id" => 17019
    "hazard_score" => 4
    "hazard_video_name" => "Clip 2"
    "hazard_video_id" => 111860215
    "hazard_video_section" => "theory"
    "created_at" => "2017-09-05 08:39:26"
    "updated_at" => "2017-09-05 08:39:26"
    "deleted_at" => null
  ]
  2 => array:9 [
    "hazard_score_id" => 4
    "user_id" => 17019
    "hazard_score" => 5
    "hazard_video_name" => "Clip 3"
    "hazard_video_id" => 111869861
    "hazard_video_section" => "theory"
    "created_at" => "2017-09-05 08:40:40"
    "updated_at" => "2017-09-05 08:40:40"
    "deleted_at" => null
  ]
  3 => array:9 [
    "hazard_score_id" => 5
    "user_id" => 17019
    "hazard_score" => 4
    "hazard_video_name" => "Clip 1"
    "hazard_video_id" => 111860212
    "hazard_video_section" => "theory"
    "created_at" => "2017-09-05 10:20:19"
    "updated_at" => "2017-09-05 10:20:21"
    "deleted_at" => null
  ]
]

我已尝试这样做,但我的号码每次只返回0。

// Get Total Score (Based on Best Scores)
$total = 0;
$best_score = 0;

foreach($scores as $score)
{
    $video_id = $score->hazard_video_id;
    $best_score = $score->hazard_score;

    if($best_score > $score->hazard_score)
    {
        $total += $best_score;
    }
}

由于

4 个答案:

答案 0 :(得分:1)

if($best_score >= $score->hazard_score)
{
    $best_score = $score->hazard_score;
    $total += $best_score;
}

$best_score始终为零,您应该更改它;同样只使用<比较,否则你将添加5次。

if($best_score < $score->hazard_score)

答案 1 :(得分:1)

我想你可能想以这种方式改变你的状况:

if( $score->hazard_score >= $best_score)

答案 2 :(得分:1)

您应该添加以下行

if ($best_score === 0)
{
    $best_score = $score->hazard_score;
}

到你的循环。这应该是

if($best_score >= $score->hazard_score)

反转。

答案 3 :(得分:1)

$total循环内添加foreach,如果视频有“下一个得分”,则无法“预测”做出决定,也不能分析得分是否更高。相反,您需要浏览整个集合以找到每个视频的最高分数,然后总计:

$best = [];
foreach($scores as $score) {
    if (!isset($best[$score->hazard_video_id])) {
        $best[$score->hazard_video_id] = 0; //assuming 0 is less then the minimal possible score. 
    }
    if ($score->hazard_score > $best[$score->hazard_video_id]) {
        $best[$score->hazard_video_id] = $score->hazard_score;
    }
}
$total = array_sum($best);