【问题标题】:Regular expression for count lesson absence of students统计学生缺课的正则表达式
【发布时间】:2016-02-10 18:58:46
【问题描述】:

我用逗号分隔值将学生缺课情况存储在数据库中。

我确实将逗号视为正则表达式来计算学生缺课的课程数。

这就是我的做法。

@foreach($students as $student)

   {{(preg_match_all('/[^,]+/',DB::table('discontinuities')
->where('student_id', $student->id)
->where('type2','absent')->pluck('type2Lesson'))) }} 
    Lessons student was absent.
@endforeach

但问题是学生可能缺席多天,这意味着多行存储在 discontinuities 表中,此查询显示唯一返回的第一个值。但我需要对总值求和以返回学生缺课的课程数

这是学生缺课的例子

这是结果查询

编辑:

如果我先输入2缺席,然后输入1缺席

那么结果就是

【问题讨论】:

  • 你想用那个正则表达式做什么,计算type2Lesson字段中逗号的数量?
  • 你怎么知道哪个输出属于哪个学生?您至少应该输出学生的姓名或 ID 或其他内容,以确保您看到的是您认为您正在查看的内容。
  • @Jeff 是的,我确实计算了逗号分隔值的数量,但在多行中。
  • @trincot 你怎么知道哪个输出属于哪个学生?我检查 ->where('student_id', $student->id)
  • 是的,但是你循环遍历学生ID,那么你怎么知道哪一行属于哪个学生ID?

标签: php regex laravel


【解决方案1】:
@foreach($students as $student)

<?php $absences = DB::table('discontinuities')
    ->select('type2Lesson')
    ->where('student_id', $student->id)
    ->where('type2','absent'))
    ->get();

    $count = 0;

    foreach($absences as $absence){
        $count += count(explode(',', $absence->type2Lesson));
    }
?>

   {{$count}} lessons student was absent.
@endforeach

这应该可行。将 json 或 CSV 格式的数据保存在数据库中并不是一个好习惯,因为您最终无法编写查询来执行您想要的操作。例如,最好有一个学生应该参加的每一堂课的数据库,以及一个表示缺席与否的布尔值。然后你就可以统计缺勤人数了。

【讨论】:

    【解决方案2】:

    您需要执行一个查询,将给定学生的缺勤记录分组在一起。我什至会让查询计算缺勤天数。它可以计算逗号,然后对该值执行标准-&gt;sum()

    @foreach($students as $student)
    
        {{ 
        DB::table('discontinuities')
        ->where('student_id', $student->id)
        ->where('type2','absent')
        ->sum(DB::raw("LENGTH(type2Lesson) - LENGTH(REPLACE(type2Lesson, ',', ''))+1")
        }}
        Lessons student was absent.
    @endforeach
    

    查询需要一个 DB::raw() 调用来计算逗号的数量。该表达式的语法取决于数据库引擎。以上适用于MySql,但对于其他数据库,您需要使用LEN 而不是LENGTH

    【讨论】:

      猜你喜欢
      • 2010-10-29
      • 2014-06-02
      • 2013-03-13
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多