Merge Two Multidimensional Arrays and Reindex All Subarrays

Merge two multidimensional arrays and reindex all subarrays

FIXED (again)

function array_merge_to_indexed () {
$result = array();

foreach (func_get_args() as $arg) {
foreach ($arg as $innerArr) {
$result[] = array_values($innerArr);
}
}

return $result;
}

Accepts an unlimited number of input arrays, merges all sub arrays into one container as indexed arrays, and returns the result.

EDIT 03/2014: Improved readability and efficiency

How to combine two multidimensional arrays with same index without merging?

You can do it like below:-

$final_array = [];

foreach($array1 as $key=>$arr){
$final_array[$key] = [$arr,$array2[$key]];
}
print_r($final_array);

How to add merge subarrays of two multi-dimensional arrays

Sadly, it takes a fair amount of iterating/preparation to get your two arrays ready for use with array_merge_recursive(). I'll admit, I'm not proud of the convolution in my method. The major factor in all this is that array_merge_recursive() only "plays nicely" with non-numeric indexes, so I had to replace your numerically indexed keys with relative id values within the arrays. I'll do my best to explain my steps, but again, it's not pretty... (Demo)

Step #1: Prepare $stock array:

foreach($stock as $subarray){
$new_stock["#{$subarray['productid']}"]=$subarray; // replace outer key
$new_variants=[]; // declare a fresh array
foreach($subarray['variants'] as $varsub){
$new_variants["#{$varsub['variantId']}"]['isInStock']=$varsub['isInStock']; // one element only
// omitting variantId element this time as the next array will offer it.
}
$new_stock["#{$subarray['productid']}"]['variants']=$new_variants;
}

Step #2: Prepare $data array & merge:

foreach($data as $subarray){
$new_data["#{$subarray['productid']}"]=$subarray; // replace outer key
$new_variants=[]; // declare a fresh array
foreach($subarray['variants'] as $varsub){
$new_variants["#{$varsub['variantId']}"]=$varsub; // both elements from variants
}
$new_data["#{$subarray['productid']}"]['variants']=array_values(array_merge_recursive($new_variants,$new_stock["#{$subarray['productid']}"]['variants']));
// new variants subarray has been merged, re-indexed, and written to $new_data
}

Step #3: re-index outer array keys, and display:

$result=array_values($new_data);    
var_export($result);

The bulk of the array preparations is to generate unique id's for the outer and inner arrays (in both $stock & $data). This permits the array_merge to isolate the related productids and recursively merge the variant elements.

If these two arrays are being generated from a database, then my high recommendation is to utilize available database functionality to merge this data instead of php.

For a simple example of how array_merge_recursive() works here's a small demo. Experiment with the keys in either of the arrays. If you so-much-as remove the # from the numeric string, array_merge_recursive() will assume that it's dealing with numeric indexes and mince things up. My technique to preserve your id's as strings was to prepend the #, but it could have been done by adding any of a range of non-digit characters to the key value.

Merge subarrays of multidimensional array based on sub value

Try using array_reduce function with callback function:

$result = array_values(array_reduce($myarray, function($rows, $item){
if (array_key_exists('messageId', $item) && is_scalar($item['messageId'])) {
$rows = array_replace_recursive($rows ?? [], [$item['messageId'] => $item]);
}
return $rows;
}));

print_r($result);

fiddle

Merge all sub arrays into one

If it's only two levels of array, you can use

$result = call_user_func_array('array_merge', $array);

which should work as long as $array isn't completely empty

Merge two multidimensional arrays, preserve numeric keys, and combine values inside array

Assuming that they will always have the same keys!

$result = array();

foreach($arr1 as $key=>$array) {
$result[$key] = array_merge($array, $arr2[$key]);
}

Merging two multidimensional arrays on specific key

You can just do a nested loop and check if the id values match, then add title to $first (or name to $second)

foreach($first as $key => $value){
foreach($second as $value2){
if($value['id'] === $value2['id']){
$first[$key]['title'] = $value2['title'];
}
}
}

How to merge subarray values and generate a 1-dimensional array of unique values?

In your desired output indexes are same, you never achieve that. because same indexes are over-written by most recent values.

You can get like below:-

$final_array = array_unique(call_user_func_array('array_merge', $array)); //convert multi-dimensional array to single dimensional and remove duplicates
asort($final_array); // sort by value. this is optional
$final_array = array_values($final_array); // re-index final array and this is optional too
echo "<pre/>";print_r($final_array); // print final array

Output:- https://eval.in/752750

Merge two indexed arrays of indexed arrays based on first column value

You can use the PHP function array_merge_recursive.
See the example:

<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>


Related Topics



Leave a reply



Submit