I had a similar need because I needed to merge n-dimensional arrays containing configuration values, so I ended up writing a function, I just expanded it a bit to apply to n-dimensional arrays.
/**
* Recursively merges $array2 to $array1 while keeping the $array2 values
* and keys unique.
*
* @param array $array1 - destination array
* @param array $array2 - array containing new values
* @return array
*/
public function arraysMergeUnique($array1, $array2)
{
foreach ($array2 as $k => $v)
{
if ( is_array($array1) )
{
// If the meaning the value is a string, and doesn't already exist, add it
if ( is_string($v) && ! in_array($v, $array1) )
{
$array1[] = $v;
}
// If the value's an array, make a recursive call with it
else if ( is_array($v) )
{
if ( isset($array1[$k]) )
{
$array1[$k] = $this->arraysMergeUnique($array1[$k], $v);
}
else
{
$array1[$k] = $v;
}
}
}
else
{
$array1 = array($v);
}
}
return $array1;
}
For example, if your list was even deeper, if 'school1' contained 'class1':
$list1 = array(
'school1' => array(
'string1',
'string2',
'class 1' => array(
'student 1',
)
)
);
$list2 = array(
'school1' => array(
'string1',
'string3',
'class 1' => array(
'student 1',
'student 2',
),
'class 2' => array(
'student 3',
),
),
'school2' => array(
'string1',
'string4',
'string5'
)
);
the resulting array would merge it fully:
$result = array(
'school1' => array(
'string1',
'string2',
'class 1' => array(
'student 1',
'student 2'
),
'string3',
'class 2' => array(
'student 3'
)
),
'school2' => array(
'string1',
'string4',
'string5'
)
);
The function should probably be written so that it works with references, and not values like this one, which would greatly improve performance with big arrays, but this one works just fine with smaller ones.
$list2['school1'], only$list1['school1'].string3in the second array? As is the standardarray_mergefunction will do it and nothing about this is specifically "multidimensional merging".