2
\$\begingroup\$

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
        )

)
\$\endgroup\$
2
  • \$\begingroup\$ Is array_merge is not helpful to you ? \$\endgroup\$ Commented Mar 4, 2016 at 9:27
  • 1
    \$\begingroup\$ @AlankarMore I'm already using array_merge in this function; using array_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\$
    – allejo
    Commented Mar 4, 2016 at 19:40

2 Answers 2

4
\$\begingroup\$

There is an alternative to your implementation. If you can change the position of the name element to the array key:

$defaults = array(
    'foo' => array(
        "level" => 5,
        "meta" => array(
            "value" => 1
        )
    ),
    'bar' => array(
        "level" => 6
    )
);

$custom = array(
    'qux' => array(
        "date" => "2016-01-01"
    ),
    'tux' => array(
        "date" => "2016-01-31"
    ),
    'foo' => array(
        "date" => "2015-01-01",
        "meta" => array(
            "value" => 5,
            "something" => "hello world"
        )
    )
);

You can utilize the native PHP function: array_replace_recursive

Using this function will provide you with the same resulting structure as you have shown with the exception of having the names as array keys. If this is an issue to you, you can duplicate the name once more into an array element.

The reason this specific/unique key is required is to only merge elements related to each other.

This little snippet should translate your array into the required structure:

/**
 * Translates an array element into an unique key for the element.
 *
 * (The name is just an example)
 */
function uniqify(array $array, string $key): array
{
    foreach($array as $index => $value)
    {
        $array[$value[$key]] = $value;
        unset($array[$index]);
    }
    return $array;
}

You could then so something like this:

$merged = array_replace_recursive(
    uniqify($defaults, 'name'),
    uniqify($custom,   'name')
);

Hope this can help, happy coding!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ you are passing second arg $key but you never use that inside that function :) \$\endgroup\$ Commented Sep 28, 2018 at 22:38
0
\$\begingroup\$

Although this one is a little older already, I had the same problem yesterday and solved it recursively. No items of $base will be overwritten.

private function associativeMerge(iterable $base, iterable $addition) : iterable
{
    foreach($addition as $key => $sub)

        if(! array_key_exists($key, $base) ) 
            $base[$key] = $sub;
        elseif( is_array($base[$key]) && is_array($addition[$key]) )
            $base[$key] = associativeMerge($base[$key], $addition[$key]);

    return $base;
}

Maybe this helps anyone...

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.