Skip to content

Instantly share code, notes, and snippets.

@groovili
Last active December 14, 2017 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save groovili/42a4dfe6d106ada590de2449e91990c5 to your computer and use it in GitHub Desktop.
Save groovili/42a4dfe6d106ada590de2449e91990c5 to your computer and use it in GitHub Desktop.
<?php
function cm(array $ar1, array $ar2, int $rc = 0): array
{
$duplicatePositions = [];
$merged = [];
foreach($ar1 as $key => &$value){
if($dk = array_search($value, $ar2, true)){
$duplicatePositions[$dk] = $ar2[$dk];
}
if(is_array($value)){
$value = cm($value, $ar2, $rc++);
}
$merged[$key] = $value;
}
foreach($ar2 as $key => $value){
if(array_search($key, $duplicatePositions)){
continue;
}
$merged[$key] = $value;
}
$rc--;
return $merged;
}
$ar1 = array("color" => array("red", "green"));
$ar2 = array("color" => array("green", "blue"));
print_r(array_merge($ar1,$ar2));
print_r(cm($ar1,$ar2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment