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
)
Merging two PHP arrays with same numeric key
You can try below code to merge array. Code generates desired output required to you. I have used sample array as given by you:
<?php
$arr1=array(
"384"=>array("name"=>"SomeMovieName1","age"=>"12.2 hrs","IMDBLink"=>"","IMDBRating"=>"", "coverArt"=>""),
"452"=>array("name"=>"SomeMovieName2","age"=>"15.2 hrs","IMDBLink"=>"","IMDBRating"=>"", "coverArt"=>""),
"954"=>array("name"=>"SomeMovieName3","age"=>"4.2 hrs","IMDBLink"=>"","IMDBRating"=>"", "coverArt"=>"")
);
$arr2=array(
"384" => array("IMDBLink" => "7.2", "IMDBRating" => "http://www.imdb.com/LinkToMovie1", "coverArt" => "http://www.SomeLinkToCoverArt.com/1"),
"452" => array("IMDBLink" => "5","IMDBRating" => "http://www.imdb.com/LinkToMovie2", "coverArt" => "http://www.SomeLinkToCoverArt.com/2"),
"954"=>array("IMDBLink" => "8","IMDBRating" => "http://www.imdb.com/LinkToMovie3", "coverArt" => "http://www.SomeLinkToCoverArt.com/3")
);
$arr3 = array();
foreach($arr1 as $key=>$val)
{
$arr3[] = array_merge($val, $arr2[$key]);
}
echo "<pre>";
print_r($arr3);
?>
Combining values from two arrays with same keys
If you can guarantee these two arrays will always have the same keys:
$arr3 = array();
foreach ($arr1 as $key => $val1) {
$val2 = $arr2[$key];
$arr3[$key] = $val1 . "-" . $val2;
}
Now, assuming the two have different keys and you want to do a "joined" array with only the keys that exist in both arrays:
$arr3 = array();
foreach (array_intersect(array_keys($arr1), array_keys($arr2)) as $key) {
$arr3[$key] = $arr1[$key] . "-" . $arr2[$key];
}
This is similar to a SQL inner join.
If you want to do a "joined" array with the keys in either of the arrays, hyphen-joining only the ones that exist in both:
$arr3 = array();
foreach (array_merge(array_keys($arr1), array_keys($arr2)) as $key) {
if (isset($arr1[$key]) && isset($arr2[$key])) {
$arr3[$key] = $arr1[$key] . "-" . $arr2[$key];
} else {
$arr3[$key] = (isset($arr1[$key]) ? $arr1[$key] : $arr2[$key]);
}
}
This is similar to a SQL outer join.
Try all of the above online!
How to merge two arrays and sum the values of duplicate keys?
I think the problem is simpler than it looks. You really only need a conditional to preclude undefined offset notices. Just iterate all keys and values in both arrays and add the values to the corresponding key in the merged array.
foreach ([$a1, $a2] as $a) { // iterate both arrays
foreach ($a as $key => $value) { // iterate all keys+values
$merged[$key] = $value + ($merged[$key] ?? 0); // merge and add
}
}
Really, the line that actually does the addition ($merged[$key] = $value + ($merged[$key] ?? 0);
) could be reduced to $merged[$key] += $value;
. That would still work, but it would produce a bunch of undefined offset notices. So instead we can set the key equal to the value plus either the previous value (if it exists) or zero.
If you're still using PHP 5, you can use a ternary instead of the null coalescing operator (??
), like this:
$merged[$key] = $value + (isset($merged[$key]) ? $merged[$key] : 0);
The output won't be in the same order shown in your desired result, but you can use ksort($merged);
to accomplish that
Merging couple different arrays with same keys into one array
If you want merge two records in single array take one array variable and change your loop as below.
$skus = [];
foreach($apiS->sku as $skuname=>$skuvalue) {
$skus[$skuname]['promotion_price'] = $skuvalue->price->priceText;
$skus[$skuname]['quantity'] = $skuvalue->quantity;
}
foreach($apiD->sku as $skuname=>$skuvalue) {
$skus[$skuname]['price'] = $skuvalue->price->priceText;
}
Merge arrays under same key
You can use the following :
map(to_entries) | add | group_by(.key) | map({ key: (.[0].key), value:([.[].value | add]) }) | from_entries
Try it here.
map(to_entries)
change each of your files into an array of key/value pairs.
add
merge those two arrays into one.
group_by(.key)
changes the content of the array into multiple arrays that regroup the objects with the same key.
map({ key: (.[0].key), value:([.[].value | add]) })
transforms those arrays into an object with a key/value pair whose key is the original key and the value is the merged values of the different objects with that key.
from_entries
recreates an object from the array of key/value objects.
Merge two arrays of objects with the same keys in JavaScript
Your third try [arr1, arr2]
was really close to a right answer, you can use the new spread syntax (...)
to concat the arrays by doing to following:
const arr1 = [{ label: "one", value: "one", type: "arr1" }];
const arr2 = [{ label: "two", value: "two", type: "arr1" }];
console.log([...arr1, ...arr2]);
Merge two 2d arrays on shared value from different keys
Deceze's solution is perfect if the two arrays are synchronized (i.e. items with matching code
and model
are at the same index in both arrays). If that is not the case you will need more than one line of code.
The arrays need to have string keys in order to be merged with array_merge
. In this case you want to rekey the first one based on code
and the second based on model
. After rekeying you can merge them with array_merge_recursive
.
Rekeying is easy in PHP 5.5+:
// array_column will conveniently rekey when the second argument is null
$array1 = array_column($array1, null, 'code');
$array2 = array_column($array2, null, 'model');
A bit more complicated in earlier versions:
// array_map is a more complicated way to extract a column from an array
// and array_combine will do the rekeying
$array1 = array_combine(
array_map(function($i) { return $i['code']; }, $array1),
$array1);
$array2 = array_combine(
array_map(function($i) { return $i['model']; }, $array2),
$array2);
In both cases the final step would be the same:
$result = array_merge_recursive($array1, $array2);
Related Topics
Why Doesn't MySQL Support Millisecond/Microsecond Precision
PHPmailer - Ssl3_Get_Server_Certificate:Certificate Verify Failed
How to Make This Preg_Match Case Insensitive
Why Is This PHP Call to Json_Encode Silently Failing - Inability to Handle Single Quotes
Sort and Display Directory List Alphabetically Using Opendir() in PHP
Prevent Sent Emails Treated as Junk Mails Using PHP Mail Function
Why Are $_Post Variables Getting Escaped in PHP
Detect Exact Os Version from Browser
Adding Months to a Date in JavaScript
PHP Array Merge Two Arrays on Same Key
PHP, MySQL Error: Column Count Doesn't Match Value Count At Row 1
How to Strip a Tag and All of Its Inner HTML Using the Tag'S Id
How to Successfully Rewrite Old MySQL-PHP Code With Deprecated MySQL_* Functions
Use One Bind_Param() With Variable Number of Input Vars
PHP Get All the Images from Url Which Width and Height ≫=200 More Quicker