PHP, Merging arrays with common keys
function merge_common_keys(){
$arr = func_get_args();
$num = func_num_args();
$keys = array();
$i = 0;
for ($i=0; $i<$num; ++$i){
$keys = array_merge($keys, array_keys($arr[$i]));
}
$keys = array_unique($keys);
$merged = array();
foreach ($keys as $key){
$merged[$key] = array();
for($i=0; $i<$num; ++$i){
$merged[$key][] = isset($arr[$i][$key]) ? $arr[$i][$key] : null;
}
}
return $merged;
}
Usage:
$merged = merge_common_keys($array1,$array2);
PS. It can work with more than two arrays, just pass as many as you want as next arguments.
PHP : merge multiples arrays with common keys
If the order of both arrays is the same, you can simply use
$array_final = array_replace_recursive($array1, $array2);
However, if you want to merge them by the "id", you need to loop through them. A solution with the complexity O(m*n):
$array_final = array();
// loop through all movies in array1
foreach($array1 as $movie){
foreach($array2 as $movie_release) {
if ($movie['id'] == $movie_release['id']) {
$movie['releasedate'] = $movie_release['releasedate'];
break;
}
}
$array_final[] = $movie;
}
And a little less complex O(m+n):
// create arrays with the ID as key
$titles = array_column($array1, 'title', 'id');
$releasedates = array_column($array2, 'releasedate', 'id');
$array_final = array();
foreach($titles as $id => $title) {
$array_final[] = array(
'id' => $id,
'title' => $title,
'releasedate' => $releasedates[$id]
);
}
Merge array with common value
The first function that comes to mind is array_merge_recursive()
, but even if you assign temporary associative keys to the subarrays, you end up with multiple January
values in a new deep subarray.
But do not despair, there is another recursive function that can do this job. array_replace_recursive()
will successfully merge these multidimensional arrays so long as temporary associative keys are assigned first.
Here is a one-liner that doesn't use foreach()
loops or if statements:
Code: (Demo)
$arr=json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]',true);
$arr2=json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]',true);
echo json_encode(array_values(array_replace_recursive(array_column($arr,NULL,'month'),array_column($arr2,NULL,'month'))));
Output:
[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}]
The breakdown:
echo json_encode( // convert back to json
array_values( // remove the temp keys (reindex)
array_replace_recursive( // effectively merge/replace elements associatively
array_column($arr,NULL,'month'), // use month as temp keys for each subarray
array_column($arr2,NULL,'month') // use month as temp keys for each subarray
)
)
);
merge two arrays have a common key
$arrayA = array("avg" => "234","shape" => "hey");
$arrayB = array("avg" => "5678","shape" => "trapezoid");
$array3 = array();
foreach ($arrayA as $key => $value) {
$array3[$key] = array($arrayA[$key], $arrayB[$key]);
}
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
Merge multidimensional objects with common indexes
This is only an example, to explain how you can use function multiArrayCombine
from my answer to another question:
foreach( $array['a']['entries'] as &$val ) $val = (array) $val;
foreach( $array['b']['entries'] as &$val ) $val = (array) $val;
$result = multiArrayCombine( $array['a']['entries'], $array['b']['entries'], T_OBJECT_CAST );
$array['a']['entries'] = $result;
unset( $array['b'] );
print_r( $array );
eval.in demo
As I said, this is only an example: the function has the option to return objects but not to analyze it. You can modify it to process also objects and use it directly, without above first two lines.
Merging arrays with the same keys
Try with array_merge_recursive
$A = array('a' => 1, 'b' => 2, 'c' => 3);
$B = array('c' => 4, 'd'=> 5);
$c = array_merge_recursive($A,$B);
echo "<pre>";
print_r($c);
echo "</pre>";
will return
Array
(
[a] => 1
[b] => 2
[c] => Array
(
[0] => 3
[1] => 4
)
[d] => 5
)
Related Topics
What Means Call to a Member Function on Boolean and How to Fix
How to Stop PHP Sleep() Affecting My Whole PHP Code
Parse Error: Syntax Error, Unexpected '' (T_Encapsed_And_Whitespace)
Detect If Uploaded File Is Too Large
Trying to Pass Todataurl with Over 524288 Bytes Using Input Type Text
Any Way to Break If Statement in PHP
Use Keyword in Functions - PHP
PHP Not Loading PHP_Pgsql.Dll on Windows
How to Perform Multiple Guzzle Requests at the Same Time
Protocol Https Not Supported or Disabled in Libcurl
MySQL Group by and Fill Empty Rows
Is There Any JavaScript Tcp Soket Library for PHP Like Signalr with .Net
Html5 Audio Says "Live Broadcast" in iOS When It's a Static File