I have an array in PHP. My array is the above:
| Student First Name |Student Last Name | Age |Disability|
| Student_First_Name_1 |Student_Last_Name_1 | 30 | 1 |
| Student_First_Name_2 |Student_Last_Name_2 | 28 | 0 |
| Student_First_Name_3 |Student_Last_Name_3 | 21 | 0 |
| Student_First_Name_4 |Student_Last_Name_4 | 20 | 1 |
and I want from this array to compare the entries and make groups and save them to database. So the student_1 with entry 1 will be grouped with the Student_4 with entry 1 and the Student_2 with the Student_3.
My code is the above:
$count=count($TempSelected);
for($i=1,$j=0;$i<$count;$i++){
if($TempSelected[$j]['disability']==$TempSelected[$i]['disability']){
if( abs($TempSelected[$j]['age']-$TempSelected[$i]['age']) <= 23 ){
$Student1 = $TempSelected[$j]['first_name'].' '.$TempSelected[$j]['last_name'];
$Student2 = $TempSelected[$i]['first_name'].' '.$TempSelected[$i]['last_name'];
unset($TempSelected[$i]);
unset($TempSelected[$j]);
$FirstEntry = $conn->prepare("SELECT id FROM ".$TableName." WHERE Checked = 0 LIMIT 1");
$FirstEntry->execute();
$id = $FirstEntry->fetchColumn();
$data = [
'student_1' => $Student1,
'student_2' => $Student2,
'Checked' => 1,
'id' => $id,
];
$AddStudent = $conn->prepare("UPDATE ".$TableName." SET student_1=:student_1, student_2=:student_2, Checked=:Checked WHERE id=:id");
$AddStudent->execute($data);
}
}
$count=count($TempSelected);
}
But it only make a group and stops.
I want to stops when it make all the groups not only 1.
Can you help me?
I edit my array above and I entered exactly what I have in the array
You need to use nested loops to compare all the pairs of elements. Your code increments $i
, but $j
is always 0
, so you're only comparing with the first student.
for ($i = 0; $i < $count-1; $i++) {
for ($j = $i+1; $j < $count; $j++) {
...
}
}