php - Merge 2 arrays: don't change indexes and add the 2nd values in order in the gaps -


i have 2 arrays. want not change indexes of first 1 , second one, added order in gaps of missing indexes:

$a = array(      0 => 9,      2 => 13      );  $b = array(      1 => 10,      2 => 11,      3 => 12,      4 => 1      ); 

i want result:

$ab = array(       0 => 9,        1 => 10,        2 => 13,        3 => 11,        4 => 12,        5 => 1       ); 

i tried this:

$ab = $a+$b;    // keeps indexes, removes key 2 array $ b $ab = array_merge($a, $b);  // change indexes $ab = array_unique(array_merge($a,$b));     // change indexes $ab = array_merge($a, array_diff($b, $a));  // change indexes 

loop through $b, copying elements $a. if index exists, increment adjustment new index.

function mergearrays($a, $b) {     $adjust = 0;     foreach ($b $i => $val) {         while (isset($a[$i + $adjust])) {             $adjust++;         }         $a[$i + $adjust] = $val;     }     ksort($a); // put in order new indexes     return $a; } 

demo


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -