首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于较高数目的Foreach循环增量总数

基于较高数目的Foreach循环增量总数
EN

Stack Overflow用户
提问于 2017-09-05 09:43:21
回答 4查看 160关注 0票数 0

我正在计算分数,只想收集更高的分数。这是拉勒维尔收藏的。

我现在有4分。

5,4,5,4

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

我的数组看起来如下:

代码语言:javascript
复制
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。

代码语言:javascript
复制
// 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;
    }
}

谢谢

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2017-09-05 10:04:55

$total添加到foreach循环中,您不能“向前看”来决定视频中是否有“下一个分数”,也不能分析该分数是否更高。相反,您需要查看整个集合,以找到每个视频的最高得分,然后将它们合计:

代码语言:javascript
复制
$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);
票数 1
EN

Stack Overflow用户

发布于 2017-09-05 09:47:43

代码语言:javascript
复制
if($best_score >= $score->hazard_score)
{
    $best_score = $score->hazard_score;
    $total += $best_score;
}

$best_score总是为零,您应该修改它;也只使用<比较,否则您将添加5次,两次。

代码语言:javascript
复制
if($best_score < $score->hazard_score)
票数 1
EN

Stack Overflow用户

发布于 2017-09-05 09:47:47

我想你可能会想改变你的状况,这样:

代码语言:javascript
复制
if( $score->hazard_score >= $best_score)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46051834

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档