0

I need to merge (sort of join) two arrays with both same keys, and in result i want to have the values of the first as keys of the second one :

Example :

$keyArray = [ "key1" => "map1", "key2" => "map1", "key3" => "map2", "key4" => "map3" ];

$valuesArray = [ "key1" => "value1", "key2" => "value2", "key3" => "value3", "key4" => "value3" ];

// expected result :

$mappedResultArray = 
[
  "map1" => [
    "value1",
    "value2"
  ],
  "map2" => [
    "value3"
  ],
  "map3" => [
    "valu3"
  ],
];

I know that this is possible by using php loops/foreach through both arrays, But I want to have a solution using PHP array_* functions (array_map, array_merge ....)

1 Answer 1

1

You can do this using array_walk with closure see example below :

$keyArray = [ "key1" => "map1", "key2" => "map1", "key3" => "map2", "key4" => "map3" ];

$valueArray = [ "key1" => "value1", "key2" => "value2", "key3" => "value3", "key4" => "value3" ];

function getMergeByKeys($keyArray, $valueArray) {
    $mapped = [];
    array_walk(
        $keyArray, 
        function($key, $value) use ($valueArray, &$mapped) {
            $mapped[$key][] = $valueArray[$value];
        });
    return $mapped;
}

print_r(getMergeByKeys($keyArray, $valueArray));

It will result :

Array
(
    [map1] => Array
        (
            [0] => value1
            [1] => value2
        )

    [map2] => Array
        (
            [0] => value3
        )

    [map3] => Array
        (
            [0] => value3
        )

)

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.