开发者

Merge two arrays

开发者 https://www.devze.com 2023-02-11 04:51 出处:网络
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 checki

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.


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:

  • Your first conditional is backwards. If the value is already in array 2, you want to do nothing, instead you're doing nothing when it's missing and should be added.
  • You make a lot of use of double quoted strings when concatenation would be cleaner (easier to read and harder to make unnoticed mistakes).
  • You issue an UPDATE query every time you change $results2 when you only need to update it once, after building the whole string.
  • You quote what appear to be numeric values in the query ($r2_id). MySQL won't complain about it, but you might be surprised when the implicit conversion from a string to a number doesn't yield the result you expected.
  • You don't need an else clause if there's nothing in it.
  • Storing a serialized array in a column of a database table in the first place is usually a wrong thing to do.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号