Skip to content

Instantly share code, notes, and snippets.

@CWSpear
Created September 18, 2012 19:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CWSpear/3745161 to your computer and use it in GitHub Desktop.
Save CWSpear/3745161 to your computer and use it in GitHub Desktop.
object_merge for php
<?php
$one->one = 1;
$two->two->one = 21;
$two->two->two = 22;
$three->two->one = 31;
$return_obj = object_merge($one, $two, $three);
// returns:
// Array
// (
// [one] => 1
// [two] => Array
// (
// [one] => 31
// )
//
// )
$a_one['one'] = 1;
$a_two['two']['one'] = 21;
$a_two['two']['two'] = 22;
$a_three['two']['one'] = 31;
$return_arr = array_merge($a_one, $a_two, $a_three);
// returns:
// stdClass Object
// (
// [one] => 1
// [two] => stdClass Object
// (
// [one] => 31
// )
//
// )
// just like array_merge, you can pass in as many objects (instead of arrays) as you want
function object_merge()
{
// so we can pass in any number of parameters
$params = func_get_args();
// convert each parameter to an array
foreach ($params as $key => $value)
{
$params[$key] = (array) $value;
}
// do a classic array_merge and cast to an object
return (object) call_user_func_array(array_merge, $params);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment