Skip to content

Instantly share code, notes, and snippets.

@fernando-jascovich
Last active December 15, 2015 07:29
Show Gist options
  • Select an option

  • Save fernando-jascovich/5224222 to your computer and use it in GitHub Desktop.

Select an option

Save fernando-jascovich/5224222 to your computer and use it in GitHub Desktop.
Beautiful php array_merge function
<?php
function merge_arrays($array1, $array2)
{
$return_array = array();
$key_array = array();
foreach($array1 as $key => $value)
{
$return_array[$key] = $value;
foreach ($value as $sub_key => $sub_value)
{
if(!array_key_exists($sub_key, $key_array))
$key_array[$sub_key] = null;
}
}
foreach($array2 as $key => $value)
{
if(array_key_exists($key, $return_array))
{
foreach($value as $sub_key => $sub_value)
{
if(!array_key_exists($sub_key, $return_array[$key]))
$return_array[$key]->$sub_key = $sub_value;
if(!array_key_exists($sub_key, $key_array))
$key_array[$sub_key] = null;
}
}
else
{
$return_array[$key] = $value;
}
}
foreach($return_array as $key => $value)
{
foreach($key_array as $sub_key => $sub_value)
{
if(!array_key_exists($sub_key, $value))
$value->$sub_key = $sub_value;
}
}
return $return_array;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment