Last active
December 15, 2015 07:29
-
-
Save fernando-jascovich/5224222 to your computer and use it in GitHub Desktop.
Beautiful php array_merge function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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