tags:

views:

541

answers:

2

Hi, I have two arrays...

$arr1 = array(
    'name',
    'date' => array('default' => '2009-06-13', 'format' => 'short'),
    'address',
    'zipcode' => array('default' => 12345, 'hidden' => true)
);

$arr2 = array(
    'name',
    'language',
    'date' => array('format' => 'long', 'hidden' => true),
    'zipcode' => array('hidden' => false)
);

Here's the desired result:

$final = array(
    'name',
    'date' => array('default' => '2009-06-13', 'format' => 'long', 'hidden' => true),
    'zipcode' => array('default' => 12345, 'hidden' => false)
);
  • Only the elements from $arr2 (that also exist in $arr1) are used
  • Each element's attributes are merged
  • If a common element (e.g. zipcode) shares an attribute (e.g. hidden), then the attribute from $arr2 takes precedence

What are some good approaches for solving this problem?

Thanks in advance.

EDIT: I tried to hobble something together... critiques welcomed:

$new_array = array_intersect_key($arr2, $arr1);

foreach ($new_array as $key => $val)
{
    if (is_array($arr1[$key]))
    {
        if (is_array($val))
        {
            $new_array[$key] = array_merge($val, $arr1[$key]);
        }
        else
        {
            $new_array[$key] = $arr1[$key];
        }
    }
}
A: 

you might find array_intersect() useful

link text

Charles Ma
I'm assuming he knows about the function by the fact a subset of such is included in his example code.
Ian Elliott
+1  A: 

You were close

$newArr = array_intersect_key($arr1, $arr2);
foreach ($newArr as $key => $val)
{
    if (is_array($val))
    {
     $newArr[$key] = array_merge($arr1[$key], $arr2[$key]);
    }
}

Edit Just had to change the array_intersect to array_intersect_key

Ian Elliott
That doesn't look quite right either. If $arr1['address'] is an array, then it still makes it to the final output... :\
Matt
I didn't really check it throughly, it just gave me the proper result so I stopped :x. Let me have another look.
Ian Elliott