Home > Article > Backend Development > How can I merge two PHP arrays with matching keys into a single array, preserving the key-value pairs from both arrays?
Merging Arrays with Matching Keys in PHP
Problem Statement:
To merge two PHP arrays with matching keys into a single array, while preserving the key-value pairs from both arrays.
Example Arrays:
Array 1:
<code class="php">array( [ "Camera1" => "192.168.101.71" ], [ "Camera2" => "192.168.101.72" ], [ "Camera3" => "192.168.101.74" ] )</code>
Array 2:
<code class="php">array( [ "Camera1" => "VT" ], [ "Camera2" => "UB" ], [ "Camera3" => "FX" ] )</code>
Solution Using array_map:
<code class="php">$array1 = array( ["Camera1" => "192.168.101.71"], ["Camera2" => "192.168.101.72"], ["Camera3" => "192.168.101.74"], ); $array2 = array( ["Camera1" => "VT"], ["Camera2" => "UB"], ["Camera3" => "FX"] ); $results = array(); array_map(function($a, $b) use (&$results) { $key = current(array_keys($a)); $a[$key] = array('ip' => $a[$key]); $key = current(array_keys($b)); $b[$key] = array('name' => $b[$key]); $results += array_merge_recursive($a, $b); }, $array1, $array2); var_dump($results);</code>
Output:
array (size=3) 'Camera1' => array (size=2) 'ip' => string '192.168.101.71' (length=14) 'name' => string 'VT' (length=2) 'Camera2' => array (size=2) 'ip' => string '192.168.101.72' (length=14) 'name' => string 'UB' (length=2) 'Camera3' => array (size=2) 'ip' => string '192.168.101.74' (length=14) 'name' => string 'FX' (length=2)
This solution preserves the key-value pairs from both arrays and merges them into a single array. The 'array_merge_recursive' function is used to merge the arrays recursively, allowing for nested arrays.
The above is the detailed content of How can I merge two PHP arrays with matching keys into a single array, preserving the key-value pairs from both arrays?. For more information, please follow other related articles on the PHP Chinese website!