Reputation: 127
I have two arrays in two MYSQL tables. I want to loop through the first array (array1), if a value exists in the second array (array2), skip that value in the second array (array2) and continue checking. If it doesn't exists, add it to the second array (array2).
An example:
array1 = 1,2,3,4,5
array2 = 2,4,6,8,10
So we loop over array1 to check if an element exists in array2. if it doesn't add it to array 2. Therefore, the new value of array2 should be:
array2= 1,2,3,4,5,6,8,10
This is what I have done and it doesn't work. It deletes all the value of array2 and adds the new value. It doesn't ignore the common values. Please help.
$array1= explode(",", $results1);
$array2= explode(",", $results2);
foreach($array1 as $key => $value) {
if (in_array($value, $array2)) {
if ($results2 != "") {
$results2= "$results2,$value";
} else { $results2= "$value"; }
mysql_query("UPDATE datas SET results2 ='$results2'
WHERE r2_id ='$r2_id'")
or die ("Died".mysql_error());
} else {
//Do nothing
}
}
Is there anything i'm doing wrong? Please help. I have been at this for a while now.
Upvotes: 0
Views: 165
Reputation: 52372
Here's a one-liner that merges the arrays:
$merged = array_unique(array_merge(explode(",", $results1), explode(",", $results2)));
$string = implode(",", $merged);
mysql_query("UPDATE datas SET results2 = '$string' WHERE r2_id = $r2_id") or die("Died ".mysql_error());
As far as what you're doing wrong, since you asked:
$results2
when you only need to update it once, after building the whole string.Upvotes: 2