PHP Merge Arrays by Value

Merge two 2d arrays by shared column value

Use array_merge_recursive()

$array = array_merge_recursive($array1, $array2);

or make your own function (it may be faster)

function my_array_merge(&$array1, &$array2) {
$result = Array();
foreach($array1 as $key => &$value) {
$result[$key] = array_merge($value, $array2[$key]);
}
return $result;
}
$array = my_array_merge($array1, array2);
print_r($array);

PHP merge arrays based on matching value of a given index

Simplest solution to make it completely dynamic apart from ID, do like below:

$arr2 = array_column($array2, "ID");

$finalArray = array();
foreach($array1 as $arr){
$key = array_search($arr['ID'], $arr2);
if($key ===false){
$key = array_search(0, $arr2);
}
unset($array2[$key]['ID']);
$finalArray[] = array_merge($arr,$array2[$key]);
}

print_r($finalArray);

Output:- https://3v4l.org/1sDJs

How to merge arrays in PHP with a same value

Iterate your array and build the combined array of objects using user_id as the key.

foreach ($array as $entry) {

// if an entry for this user id hasn't been created in the result, add this object
if (!isset($result[$entry->user_id])) {
$result[$entry->user_id] = $entry;

// otherwise, iterate this object and add the values of its keys to the existing entry
} else {
foreach ($entry as $key => $value) {
$result[$entry->user_id]->$key = $value;
}
}
}

Given the additional info you just gave (two separate arrays) the solution is basically the same, just merge the two arrays together first.

foreach (array_merge($array1, $array2) as $entry) { ...

(Working example at https://3v4l.org/ccdQc)

Merging arrays based on a value of the key

You can use array_replace_recursive to merge the arrays in your particular situation.

$color = array(
array('id' => 1, 'color' => 'red'),
array('id' => 2, 'color' => 'green'),
array('id' => 3, 'color' => 'blue'),
);

$size = array(
array('id' => 1, 'size' => 'SM'),
array('id' => 2, 'size' => 'XL'),
array('id' => 3, 'size' => 'MD'),
array('id' => 4, 'size' => 'LG'),
);

$merged = array_replace_recursive($color, $size);

Output:

array(4) {
[0]=>
array(3) {
["id"]=>
int(1)
["color"]=>
string(3) "red"
["size"]=>
string(2) "SM"
}
[1]=>
array(3) {
["id"]=>
int(2)
["color"]=>
string(5) "green"
["size"]=>
string(2) "XL"
}
[2]=>
array(3) {
["id"]=>
int(3)
["color"]=>
string(4) "blue"
["size"]=>
string(2) "MD"
}
[3]=>
array(2) {
["id"]=>
int(4)
["size"]=>
string(2) "LG"
}
}

Note: I used the traditional array layout because my PHP version won't support the new one yet :)

Second option

You can also use array_map. This will let you add as much arrays as you want with a little tweaking.

$merged = array_map(function ($c, $s) {
return array_merge($c, $s);
}, $color, $size);

var_dump($merged); // See output above

Get all combinations of one element from a dynamic amount of arrays

Use the following recursive function for the cartesian product of a variable number of arrays:

function array_cartesian_product(...$array)
{
if (empty($array)) return [[]];

$column = array_shift($array);
$cartesian = array_cartesian_product(...$array);

$result = [];
foreach ($column as $item) {
foreach ($cartesian as $row) {
array_unshift($row, $item);
array_push($result, $row);
}
}
return $result;
}

// Usage:

$a1 = ['a', 'b'];
$a2 = ['c', 'd', 'e', 'f'];
$a3 = ['g', 'h'];

$result = array_cartesian_product($a1, $a2, $a3);

print_r($result);

$a = [ ['a', 'b'], ['c', 'd', 'e', 'f'], ['g', 'h'] ];

$result = array_cartesian_product(...$a);

print_r($result);

PHP - Merge Two Associative Arrays where values match

Older & wiser: I've scrubbed my answer from years earlier because I no longer recommend the techniques. It will be most succinct and efficient to merge the arrays, feed them to a foreach() loop, then "unite" (+ is used as an array union operator) data in related rows.

The null coalescing operator (??) is used to ensure that there is always something to "unite" with.

Code: (Demo)

$result = [];
foreach (array_merge($array1, $array2) as $row) {
$result[$row['detail_image_id']] = ($result[$row['detail_image_id']] ?? []) + $row;
}

var_export(array_values($result));

Output:

array (
0 =>
array (
'detail_image_id' => '6389',
'product_name' => 'Starter broadband Package',
'guid' => 'http://xxx/wp-content/uploads/2018/04/broadband-4mbs-charji.jpg',
),
1 =>
array (
'detail_image_id' => '6358',
'product_name' => 'Starter broadband Package',
'guid' => 'http://xxx/wp-content/uploads/2018/04/broadband-4mbs-wingle.jpg',
),
)

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.

Combine two arrays

Just use:

$output = array_merge($array1, $array2);

That should solve it. Because you use string keys if one key occurs more than one time (like '44' in your example) one key will overwrite preceding ones with the same name. Because in your case they both have the same value anyway it doesn't matter and it will also remove duplicates.

Update: I just realised, that PHP treats the numeric string-keys as numbers (integers) and so will behave like this, what means, that it renumbers the keys too...

A workaround is to recreate the keys.

$output = array_combine($output, $output);

Update 2: I always forget, that there is also an operator (in bold, because this is really what you are looking for! :D)

$output = $array1 + $array2;

All of this can be seen in:
http://php.net/manual/en/function.array-merge.php

PHP: merge two arrays while keeping keys instead of reindexing?

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,
)


Related Topics



Leave a reply



Submit