PHP Array: Merging Arrays with Matching Keys
In PHP, there are instances when we need to merge multiple arrays, ensuring that items with the same key are combined. Consider the following scenario:
Problem:
We have two arrays with matching keys and wish to merge them, such as:
<code class="php">$array1 = [ ['Camera1' => '192.168.101.71'], ['Camera2' => '192.168.101.72'], ['Camera3' => '192.168.101.74'] ]; $array2 = [ ['Camera1' => 'VT'], ['Camera2' => 'UB'], ['Camera3' => 'FX'] ];</code>
Solution:
To merge these arrays while preserving the key-value relationship, we can use array_map in conjunction with array_keys to manipulate and combine them:
<code class="php">$results = array(); array_map(function($a, $b) use (&$results) { $key1 = current(array_keys($a)); $a[$key1] = ['ip' => $a[$key1]]; $key2 = current(array_keys($b)); $b[$key2] = ['name' => $b[$key2]]; $results = array_merge_recursive($a, $b); }, $array1, $array2);</code>
This solution works by looping through each element in both arrays, extracting the corresponding key, and renaming the values to ensure they can be merged using array_merge_recursive. The result is an array where each key has a merged result, as shown below:
<code class="php">array ( 'Camera1' => array ( 'ip' => '192.168.101.71', 'name' => 'VT' ), 'Camera2' => array ( 'ip' => '192.168.101.72', 'name' => 'UB' ), 'Camera3' => array ( 'ip' => '192.168.101.74', 'name' => 'FX' ) )</code>
The above is the detailed content of How to merge PHP arrays with matching keys and combine their values?. For more information, please follow other related articles on the PHP Chinese website!