Home > Software design >  How can I merge two associative array
How can I merge two associative array

Time:02-21

I have two arrays like this:

$arr1 = ['a' => '1','b' => 2];
$arr2 = ['h' => 'c','j' => '3'];

And I want to merge them to this result:

$newArr = ['a' => '1','h'=>'c','b'=>2,'j' => '3'];

That means I want to somehow merge them that the first key of the second array would be the second key of the new array and the second key of first array would be the third key of new array...

array_merge not doing this. Any solution?

CodePudding user response:

Note that this solution will only work if the two arrays have the same length:

$arr1 = [ 'a' => '1', 'b' => 2 ];
$arr2 = [ 'h' => 'c', 'j' => '3' ];

$result = [];
for ($i = 0; $i < count($arr1); $i  ) {
  $key1 = array_keys($arr1)[$i];
  $result[$key1] = $arr1[$key1];
  $key2 = array_keys($arr2)[$i];
  $result[$key2] = $arr2[$key2];
}

print_r($result);

Output:

Array
(
    [a] => 1
    [h] => c
    [b] => 2
    [j] => 3
)

CodePudding user response:

Here is a solution that will consume the input arrays in a loop while building the new structure. You can always cache separate copies of the input if you need them elsewhere. This solution will work even if the two arrays have different lengths -- any remaining elements will be appended to the end of the result array after the loop.

Code: (Demo)

$result = [];
while ($arr1 && $arr2) {
    $result  = array_splice($arr1, 0, 1)
                 array_splice($arr2, 0, 1);
}
$result  = $arr1   $arr2;
var_export($result);

CodePudding user response:

You can use array_merge() or array_merge_recursive().

Merges the elements of one or more arrays such that the values of one array are appended to the end of the previous one. The result of the function is a new array. https://www.php.net/manual/ru/function.array-merge.php

The array_merge_recursive() function merges the elements of two or more arrays in such a way that the values ​​of one array are appended to the end of the other. Returns the resulting array.

If the input arrays have the same string keys, then the values ​​of those keys are merged into an array, and this is done recursively, so that if one of the values ​​is an array, then the function merges it with the corresponding value in the other array. However, if the arrays have the same numeric keys, each successive value will not replace the original value, but will be added to the end of the array. https://www.php.net/manual/ru/function.array-merge-recursive.php

CodePudding user response:

you can use array_merge function,which uses to merge two or more arrays into single array.

$arr1 = ['a' => '1','b' => 2];
$arr2 = ['h' => 'c','j' => '3'];
$result=array_merge($arr1,$arr2);
var_dump($result);
//output:- array(4) { ["a"]=> string(1) "1" ["b"]=> int(2) ["h"]=> string(1) "c" ["j"]=> string(1) "3" } 
  • Related