I just wrote a function that will loop through two multidimensional associative arrays and merge them together based on the key names and their values. While I'm satisfied that this function works, I have a strong feeling that it can be improved. Can I get some feedback?
<?php
function array_merge_defaults (array &$array1, array &$array2, $keyField)
{
$merged = $array1;
foreach ($array2 as $key => &$value)
{
$valueMerged = false;
foreach ($merged as $mergedKey => &$item)
{
if (is_array($item) && array_key_exists($keyField, $item) && $item[$keyField] == $value[$keyField])
{
$item = array_merge($item, $value);
$valueMerged = true;
break;
}
else if ($mergedKey == $key)
{
if (is_numeric($mergedKey))
{
$merged[] = $value;
}
else
{
$item = $value;
}
$valueMerged = true;
break;
}
}
if (!$valueMerged)
{
$merged[$key] = $value;
}
}
return $merged;
}
$defaults = array(
array(
"name" => "foo",
"level" => 5,
"meta" => array(
"value" => 1
)
),
array(
"name" => "bar",
"level" => 6
)
);
$custom = array(
array(
"name" => "qux",
"date" => "2016-01-01"
),
array(
"name" => "tux",
"date" => "2016-01-31"
),
array(
"name" => "foo",
"data" => "2015-01-01",
"meta" => array(
"value" => 5,
"something" => "hello world"
)
)
);
$merged = array_merge_defaults($defaults, $custom, 'name');
print_r($merged);
Here's how my final array looks
Array
(
[0] => Array
(
[name] => foo
[level] => 5
[meta] => Array
(
[value] => 5
[something] => hello world
)
[data] => 2015-01-01
)
[1] => Array
(
[name] => bar
[level] => 6
)
[2] => Array
(
[name] => qux
[date] => 2016-01-01
)
[3] => Array
(
[name] => tux
[date] => 2016-01-31
)
)
array_merge
in this function; usingarray_merge
doesn't merge arrays based on a key/value of a multidimensional array. If you try running it with the arrays in my example, you'll see what I mean. \$\endgroup\$