Reputation: 72961
I would like to create a new associative array with respective values from two arrays where the keys from each array match.
For example:
// first (data) array:
["key1" => "value 1", "key2" => "value 2", "key3" => "value 3"];
// second (map) array:
["key1" => "map1", "key3" => "map3"];
// resulting (combined) array:
["map1" => "value 1", "map3" => "value 3"];
$combined = array();
foreach ($data as $key => $value) {
if (array_key_exists($key, $map)) {
$combined[$map[$key]] = $value;
}
}
Is there a way to do this using native PHP functions? Ideally one that is not more convoluted than the code above...
This question is similar to Combining arrays based on keys from another array. But not exact.
It's also not as simple as using array_merge()
and/or array_combine()
. Note the arrays are not necessarily equally in length.
Upvotes: 3
Views: 1859
Reputation: 875
You can use array_intersect_key()
(https://www.php.net/manual/en/function.array-intersect-key.php).
Something like that:
$int = array_intersect_key($map, $data);
$combined = array_combine(array_values($map), array_values($int));
Also it would be a good idea ksort()
both $map
and $data
.
Upvotes: 3