简体   繁体   English

PHP比较数组中的项目

[英]PHP Compare items in an array

I have an array in PHP. 我在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. 因此,条目1的student_1将与条目1的Student_4分组,而Student_3则将Student_2分组。

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. 我想停下来,让所有的组不只是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. 您的代码使$i递增,但$j始终为0 ,因此您仅与第一个学生进行比较。

for ($i = 0; $i < $count-1; $i++) {
    for ($j = $i+1; $j < $count; $j++) {
        ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM