How can I merge two arrays (one with string => value pairs and another with int => value pairs) while keeping the string/int keys? None of them will ever overlap (because one has only strings and the other has only integers).
Here is my current code (which doesn't work, because array_merge is re-indexing the array with integer keys):
// get all id vars by combining the static and dynamic $staticIdentifications = array( Users::userID => "USERID", Users::username => "USERNAME" ); // get the dynamic vars, formatted: varID => varName $companyVarIdentifications = CompanyVars::getIdentificationVarsFriendly($_SESSION['companyID']); // merge the static and dynamic vars (*** BUT KEEP THE INT INDICES ***) $idVars = array_merge($staticIdentifications, $companyVarIdentifications);
Approach 1: Convert object into data array and merge them using array_merge() function and convert this merged array back into object of class stdClass. Note: While merging the objects using array_merge(), elements of array in argument1 are overwritten by elements of array in argument2.
To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.
You can simply 'add' the arrays:
>> $a = array(1, 2, 3); array ( 0 => 1, 1 => 2, 2 => 3, ) >> $b = array("a" => 1, "b" => 2, "c" => 3) array ( 'a' => 1, 'b' => 2, 'c' => 3, ) >> $a + $b array ( 0 => 1, 1 => 2, 2 => 3, 'a' => 1, 'b' => 2, 'c' => 3, )
Considering that you have
$replaced = array('1' => 'value1', '4' => 'value4'); $replacement = array('4' => 'value2', '6' => 'value3');
Doing $merge = $replacement + $replaced;
will output:
Array('4' => 'value2', '6' => 'value3', '1' => 'value1');
The first array from sum will have values in the final output.
Doing $merge = $replaced + $replacement;
will output:
Array('1' => 'value1', '4' => 'value4', '6' => 'value3');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With