[英]Removing an array value from nested foreach in PHP
我本質上是試圖將Array1與Array2進行比較,以找到匹配的行。 但是,兩個數組都有大約14000行(來自sql表),因此我認為邏輯上刪除一旦找到array2中的匹配行,以減少總體迭代次數,將是合乎邏輯的。
看起來像這樣:
foreach($array1 as $arrayRow){
foreach($array2 as $array2Row){
if($arrayRow['ID'] == $array2Row['ID']{
$matchfound = 1;
unset($array2,$array2Row);
}
}
}
然而,看起來,運行以上代碼完全沒有任何反應。
注意:數組1和2的數據來自兩個單獨的數據庫,並且我無法一次在兩個數據庫上運行查詢(因此必須在php中執行此操作)
看來代碼將取消設置$ array2本身,並取消循環中該行的本地副本($ array2Row)。 相反,獲取要取消設置的行的鍵,然后直接取消設置該條目:
foreach($array1 as $arrayRow){
foreach($array2 as $key => $array2Row){
if($arrayRow['ID'] == $array2Row['ID']{
$matchfound = 1;
unset($array2[$key]);
}
}
}
if條件中缺少“)”。 您可以運行此代碼,使其正常運行。
foreach($array1 as $arrayRow){
foreach($array2 as $array2Row){
if($arrayRow['ID'] == $array2Row['ID']){
$matchfound = 1;
unset($array2,$array2Row);
}
}
}
檢查此解決方案以取消設置匹配的數組元素
//Array1 is $array1
//Array2 is $array2
foreach($array1 as $key => $value){
if(in_array($value,$array2)){
unset($array2[$key]);
}
}
如果需要在不使用SQL的情況下查找匹配的行,只需將結果放入ID
為鍵的關聯數組中,然后使用array_instersect_key()即可 。
這應該是最快的方法,並且由於每個數組中都有〜14K條目-我將采用以下解決方案:
$array1 = $array2 = array();
//I assume $query1Result and $query2Result are results of sql queries from 2 databases
//put rows in arrays with ID as key
while ($row = mysqli_fetch_assoc($query1Result)) {
$array1[$row['ID']] = $row; // ID is the key in array
}
while ($row = mysqli_fetch_assoc($query2Result)) {
$array2[$row['ID']] = $row; // ID is the key in array
}
//then use this to compute the intersection
$intersected = array_intersect_key($array1, $array2);
您應該使用foreach
函數的php的$key => $value
args,因此代碼如下所示:
$matchFound = 0;
foreach($array1 as $arrKey1 => $arrVal1) {
foreach($array2 as $arrKey2 => $arrVal2) {
if ($array1[$arrKey1]['ID'] == $array2[$arrKey2]['ID']) {
$matchFound = $matchFound + 1;
unset($array2[$arrVal2]);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.