在PHP中从嵌套的foreach中删除数组值
I am essentially trying to compare Array1, with Array2, to find matching rows. However, both arrays have around 14000 rows (from sql table), so I figured it would be logical to delete matching rows in array2 once found, to reduce the number of iterations overall.
It looks something like this:
foreach($array1 as $arrayRow){
foreach($array2 as $array2Row){
if($arrayRow['ID'] == $array2Row['ID']{
$matchfound = 1;
unset($array2,$array2Row);
}
}
}
However seemingly, nothing happens at all when running the above code.
Note: The data for array 1 and 2 come from two separate databases, and I am unable to run a query on both at once (hence having to do this in php)
我实际上是在尝试将Array1与Array2进行比较,以找到匹配的行。 但是,这两个数组都有大约14000行(来自sql表),所以我认为一旦找到就删除array2中的匹配行是合乎逻辑的,以减少整体的迭代次数。 p>
它 看起来像这样: p>
foreach($ array1 as $ arrayRow){
foreach($ array2 as $ array2Row){
if($ arrayRow ['ID'] == $ array2Row ['ID'] {
$ matchfound = 1;
unset($ array2,$ array2Row);
}
}
}
code> pre>
\ n 但是看起来,在运行上面的代码时根本没有任何反应。 p>
注意:数组1和2的数据来自两个独立的数据库,我无法运行 一次查询两个(因此必须在php中执行此操作) p>
div>
It appears that code will unset $array2 itself, and the local copy of the row within your loop ($array2Row). Instead, get the key for the row you want to unset, and unset the entry directly:
foreach($array1 as $arrayRow){
foreach($array2 as $key => $array2Row){
if($arrayRow['ID'] == $array2Row['ID']{
$matchfound = 1;
unset($array2[$key]);
}
}
}
There is missing of ")" into if condition. You can run this code it is working.
foreach($array1 as $arrayRow){
foreach($array2 as $array2Row){
if($arrayRow['ID'] == $array2Row['ID']){
$matchfound = 1;
unset($array2,$array2Row);
}
}
}
Check this solution to unset matching array element
//Array1 is $array1
//Array2 is $array2
foreach($array1 as $key => $value){
if(in_array($value,$array2)){
unset($array2[$key]);
}
}
If you need to find matching rows without using SQL, just put the results in associative arrays with ID
as key, and then use array_instersect_key().
This should be the fastest way to do it, and since you have ~14K entries in each array - I'd go with the solution below:
$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);
you should make use of php's $key => $value
args of the foreach
function, so the code would be something like this:
$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]);
}
}
}