views:

36

answers:

2

given the following arrays in php, how can i best merge them together

$masterkeys = array('Key1','Key2');

$settings_foo = array(
     array('ID'=>'Key1',
           'Foo_Setting'=>'SomeValue'));

$settings_bar = array(
     array('ID'=>'Key1',
           'Bar_Setting'=>'SomeOtherValue')); 

in the end I need $masterkeys to be the combination of each of the settings_[foo|bar] arrays.

Array( ['Key1'] =  Array('Foo_Setting'=>'SomeValue','Bar_Setting'=>'SomeOtherValue') );

I do know I can use a couple foreach loops on this, but just wondering if there are a couple PHP array functions that can splice them together.

A: 

I'm not sure how your $masterkeys array plays in here, but array_merge_recursive may do what you want.

jay.lee
+1  A: 

While you can use some of PHP's array functions, your input data isn't in a very nice format. You'll have the fewest iterations (and probably best performance) by writing them yourself:

# create an array of $masterkey => array()
$result = array_combine($masterkeys, array_fill(0, count($masterkeys), array()));

# loop through each settings array
foreach (array($settings_foo, $settings_bar) as $settings)
{
  foreach ($settings as $s)
  {
    # merge the array only if the ID is in the master list
    $key = $s['ID'];
    if (array_key_exists($key, $result))    
      $result[$key] = array_merge($result[$key], $s);
  }
}

# unset all extraneous 'ID' properties
foreach (array_keys($result) as $i)
  unset($result[$i]['ID']);

var_dump($result);

As an alternative, you could look into array_map and array_filter, but due to the way the data is structured, I'm not sure they'll be of much use.

konforce
yeah, input data is not in my control. I like this.
Lucas Stark