PHP - Merge Two Arrays (Same-Length) into One Associative

PHP - Merge two arrays (same-length) into one associative?

array_combine($keys, $values)

PS: Click on my answer! Its also a link!

How can I merge two associative arrays and preserve the global order of the entries?

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' ];

$count = count($arr1);
$keys1 = array_keys($arr1);
$keys2 = array_keys($arr2);

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

print_r($result);

Output:

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

Edited based on mickmackusa's comment below.

php merge 2 arrays into one associative array

If you are willing to compromise with an array structure like this:

array(
'C28' => '1AB010050093',
'C29' => '1AB008140029'
);

Then you can use the array_combine() (Codepad Demo):

array_combine($refNumbers, $partIds);

Otherwise, you'll need to use a foreach (Codepad Demo):

$combined = array();

foreach($refNumbers as $index => $refNumber) {
if(!array_key_exists($index, $partIds)) {
throw OutOfBoundsException();
}

$combined[] = array(
'ref' => $refNumber,
'part' => $partIds[$index]
);
}

How to merge two arrays by value in PHP

You can use array_unique() & array_merge() to merge and remove duplicates :

$a = [1, 2, 3];
$b = [2, 3, 4, 5];
$array = array_unique(array_merge($a, $b));
// output [1,2,3,4,5]

Merge two associative arrays sharing keys and concatenate string values

Simple foreach will do! Check inline comments

$arr1 = ["123" => "abc"];

$arr2 = ["123" => "xyz", "456" => "lmn"];

foreach ($arr2 as $key => $value) {
if(array_key_exists($key, $arr1)) // Check if key exists in array
$arr1[$key] .= ",$value"; // If so, append
else
$arr1[$key] = $value; // otherwise, add
}

print_r($arr1);

Prints

Array
(
[123] => abc,xyz
[456] => lmn
)

Check this Eval



Related Topics



Leave a reply



Submit