oop - Merging two objects and override empty attributes (PHP) -
i have 2 objects , way our finder function works (i have call twice... 1 config key, value i.e. non multilanguage stuff. , second call multilanguage stuff) makes them this:
[config] => array ( [cfg] => config_model object ( [id] => 2 [key] => system.default.main_color [value] => #ff7c11 [deleted] => 0 ) [help] => config_model object ( [id] => [key] => [value] => [id_config] => 2 [name] => hauptfarbe [help] => die hauptfarbe ihres cis. der adminbereich erscheint in dieser farbe. [id_lang] => 1 ) )
i want compine these 2 objects one. code, gets stuff looks this:
public static function get($key) { $config['cfg'] = self::find(array('key' => $key), true); $config['help'] = self::findintable(array( 'id_lang' => language_model::getdefaultlanguage(), 'id_config' => $config['cfg']->getid() ), self::dbtranslationtable, true); return $config; // return (object) array_merge((array) $config['cfg'], (array) $config['help']); }
you can tell commented return command, tried using array_merge(). problem is, empty attributes [help] override attributes [cfg], empty again:
[config] => stdclass object ( [id] => [key] => [value] => [deleted] => 0 [id_config] => 2 [name] => hauptfarbe [help] => die hauptfarbe ihres cis. der adminbereich erscheint in dieser farbe. [id_lang] => 1 )
whereas should rather this:
[config] => stdclass object ( [id] => 2 [key] => system.defalult.main_color [value] => #ff7c11 [deleted] => 0 [id_config] => 2 [name] => hauptfarbe [help] => die hauptfarbe ihres cis. der adminbereich erscheint in dieser farbe. [id_lang] => 1 )
if need more information, please let me know.
you need filter out empty values second array, , merge what's left onto first array.
the simplest solution be:
$config['help'] = array_filter((array) $config['help']); return (object) array_merge((array) $config['cfg'], (array) $config['help']);
this uses default behaviour of array_filter()
, checks whether values evaluate false
. remove empty strings, null values, or number zero.
a safer solution check empty strings, this:
$config['help'] = array_filter((array) $config['help'], function($val) { return (string) $val != ''; }); return (object) array_merge((array) $config['cfg'], (array) $config['help']);
Comments
Post a Comment