简体   繁体   中英

PHP: create an array from values in two arrays based on matching keys

The Problem

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"];

What I've Tried

$combined = array();
foreach ($data as $key => $value) {
    if (array_key_exists($key, $map)) {
        $combined[$map[$key]] = $value;
    }
}

The Question

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.

You can use array_intersect_key() ( http://ca2.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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM