【发布时间】:2020-08-06 04:06:16
【问题描述】:
我有 N 个数组。具有 n 个grade_items 子数组。 就这样。
array:2 [
0 => array:10 [
"id" => 9
"course_id" => 6
"semester_id" => 2
"name" => "Assignment"
"total_score" => 10
"grade_items" => array:1 [
0 => array:7 [
"id" => 5
"gradelist_id" => 9
"student_course_id" => 11
"score" => 8
"created_at" => "2020-04-21T03:31:20.000000Z"
"updated_at" => "2020-04-21T20:04:10.000000Z"
]
]
]
1 => array:10 [
"id" => 10
"course_id" => 6
"semester_id" => 2
"name" => "Pop Quiz"
"total_score" => 20
"grade_items" => array:1 [
0 => array:7 [
"id" => 6
"gradelist_id" => 10
"student_course_id" => 11
"score" => null
"created_at" => "2020-04-22T00:11:17.000000Z"
"updated_at" => "2020-04-22T00:11:17.000000Z"
]
]
]
]
我正在尝试从 student_course_id 相同的每个数组中添加每个grade_item 子数组。如果只有一个 Grade_item 而没有其他具有相同 student_course_id 的项目,则它只返回一个值而不是总和。
我经历过这个thread
但这只是进一步打乱了我脑海中的逻辑。我已经在这工作了好几个星期了。
当我添加每个grade_item 的分数时,我想将该值放入另一个模型中,例如“result_model”,如下所示:
result_item [
"id" => 1,
"student_course_id" => 11,
"score" => 15 //total of grade_items from all arrays where the student_course_id's were the same
];
救命!
【问题讨论】:
-
id 来自结果模型的哪里 - 我了解 student_course_id 和分数(相同课程 id 的总和)但没有得到 id
-
它是在我创建模型的新实例时自动生成的。我只是给出了模型保存后的结构。
-
就像检查第一个数组中的第一个grade_item一样,它会搜索其他数组(不是那个子数组),寻找具有相同student_course_id的其他grade_item并将分数相加。然后使用 student_course_id 和计算的分数创建一个新的 result_item。
-
在一天结束时要求澄清;你想要按 student_course_id 分组的分数总和吗?
-
是的,没错。但不仅仅是在子数组中。
标签: php arrays laravel associative-array