php - Merge two arrays -


i have 2 arrays in 2 mysql tables. want loop through first array (array1), if value exists in second array (array2), skip value in second array (array2) , continue checking. if doesn't exists, add second array (array2).

an example:

   array1 = 1,2,3,4,5    array2 = 2,4,6,8,10 

so loop on array1 check if element exists in array2. if doesn't add array 2. therefore, new value of array2 should be:

   array2= 1,2,3,4,5,6,8,10 

this have done , doesn't work. deletes value of array2 , adds new value. doesn't ignore common values. please help.

    $array1= explode(",", $results1); $array2= explode(",", $results2); foreach($array1 $key => $value) {     if (in_array($value, $array2)) {         if ($results2 != "") {              $results2= "$results2,$value";         } else { $results2= "$value"; }           mysql_query("update datas set results2 ='$results2'                      r2_id ='$r2_id'")                     or die ("died".mysql_error());     } else {         //do nothing     } } 

is there i'm doing wrong? please help. have been @ while now.

here's one-liner merges arrays:

$merged = array_unique(array_merge(explode(",", $results1), explode(",", $results2))); $string = implode(",", $merged);  mysql_query("update datas set results2 = '$string' r2_id = $r2_id") or die("died ".mysql_error()); 

as far you're doing wrong, since asked:

  • your first conditional backwards. if value in array 2, want nothing, instead you're doing nothing when it's missing , should added.
  • you make lot of use of double quoted strings when concatenation cleaner (easier read , harder make unnoticed mistakes).
  • you issue update query every time change $results2 when need update once, after building whole string.
  • you quote appear numeric values in query ($r2_id). mysql won't complain it, might surprised when implicit conversion string number doesn't yield result expected.
  • you don't need else clause if there's nothing in it.
  • storing serialized array in column of database table in first place usually wrong thing do.

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -