![](/img/trans.png)
[英]How can I add an item into a Laravel Eloquent Collection by index?
[英]Getting position or index value of an item in an eloquent collection
拜托我需要你的幫忙。 我正在嘗試從 eloquent 集合數組中獲取學生的 position。
$class_subject_marks_for_position =
App\Models\StudentMarks::where('year_id',$mark->year_id)
->where('class_id',$mark->class_id)
->where('exam_type_id',$mark->exam_type_id)
->where('assign_subject_id',$mark->assign_subject_id)
->pluck('marks')->toArray();
這將返回一個值數組,例如 55、77、99 等所有學生的分數
我還有第二個變量
$student_subject_marks_for_position =
App\Models\StudentMarks::where('year_id',$mark->year_id)
->where('class_id',$mark->class_id)
->where('exam_type_id',$mark->exam_type_id)
->where('assign_subject_id',$mark->assign_subject_id)
->where('student_id',$mark->student_id)
->value('marks');
這將為該特定學生返回一個類似 55. 的值。
現在我想要另一個變量或類似的東西,這將在第一個變量中獲得 55 的 position。 那將返回類似 1 的內容。
任何幫助將不勝感激
{55, 77, 99} 中 55 的索引是第 0 個索引,您可以從下面的代碼中獲得
for($i = 0; $i <= count($class_subject_marks_for_position); $i++){
if($student_subject_marks_for_position == $class_subject_marks_for_position[$i]){
$position = $i;
break;
}
}
您可以使用array_search function。
在數組中搜索給定的值,如果成功則返回第一個對應的鍵
$index_of_55_in_first_array = array_search(
$student_subject_marks_for_position, //The value to search
$class_subject_marks_for_position) //The array
此外,驗證索引是否為.== 為 FALSE,因為 0 是有效索引,但也是錯誤值。
此 function 可能返回 Boolean 假,但也可能返回非布爾值,其計算結果為假 (0)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.