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 ....)

asked Feb 4, 2022 at 13:03

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
 )
)
answered Feb 4, 2022 at 13:55

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.