[英]PHP in_array not working properly?
I'm working on in_array() method. 我正在研究in_array()方法。 If the value read is already in the array it should be skipped and proceed to the next value.
如果读取的值已在数组中,则应跳过该值并继续下一个值。 If the current value is not on the array yet, it should be pushed to the array.
如果当前值不在阵列上,则应将其推入阵列。
here's my code: 这是我的代码:
while ($Result_Data_2 = mysqli_fetch_array($Result)){ //130 rows from database
$Res_Array = array();
$SQL_Result_Time = $Result_Data_2['Interpretation_Time'];
/* Some statements here */
if(in_array($SQL_Result_Time, $Res_Array, true)){
break;
}
else{
array_push($Res_Array, $Number, $SQL_Questionnaire_ID, $SQL_User_ID, $SQL_Psychology_FirstName, $SQL_Psychology_LastName, $SQL_Result_Date, $SQL_Result_Time);
}
echo "<pre>";print_r($Res_Array);echo "</pre>";
}
Problem: It seems that it ignores my condition which is if(in_array($SQL_Result_Time, $Res_Array, true)){break; }
问题:似乎它忽略了我的条件,即
if(in_array($SQL_Result_Time, $Res_Array, true)){break; }
if(in_array($SQL_Result_Time, $Res_Array, true)){break; }
and still inserts the value into the array. if(in_array($SQL_Result_Time, $Res_Array, true)){break; }
和仍然插入值到阵列。 It still duplicates data 它仍然重复数据
Question: 题:
You are re-initialising your array on every iteration of the while loop
. 您将在
while loop
每次迭代中重新初始化数组。 You should declare it outside of the loop: 您应该在循环外声明它:
$Res_Array = array();
while ($Result_Data_2 = mysqli_fetch_array($Result)){ //130 rows from database
$SQL_Result_Time = $Result_Data_2['Interpretation_Time'];
/* Some statements here */
if(in_array($SQL_Result_Time, $Res_Array, true)){
break;
}
else{
array_push($Res_Array, $Number, $SQL_Questionnaire_ID, $SQL_User_ID, $SQL_Psychology_FirstName, $SQL_Psychology_LastName, $SQL_Result_Date, $SQL_Result_Time);
}
echo "<pre>";print_r($Res_Array);echo "</pre>";
}
Also, as mentioned by Marvin Fischer in his answer, your break
statement will terminate the while loop
on the first duplicated value. 同样,正如Marvin Fischer在他的回答中提到的那样,您的
break
语句将在第一个重复值上终止while loop
。 You should instead use continue
您应该改为使用
continue
while ($Result_Data_2 = mysqli_fetch_array($Result)){ //130 rows from database
...
if(in_array($SQL_Result_Time, $Res_Array, true)){
continue;
}
....
}
This question should clarify any issues you have with break
and continue
statements 这个问题应该阐明您在
break
和continue
语句中遇到的任何问题
首先,在循环内应使用continue,否则请取消整个循环,其次在每个循环的开头清空$Res_Array
以清除旧数据,插入新数据并再次回显
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.