PHP Array Merge on Same Key: A Solution Using array_map
In PHP, merging arrays can be challenging when the arrays share common keys. Let's address this problem with a solution that leverages the array_map function.
Objective:
Merge two arrays, $array1 and $array2, based on shared keys (e.g., "Camera1", "Camera2"), and ensure the merged result maintains the desired structure.
Solution:
array_map offers a way to iterate over multiple arrays simultaneously, applying a callback function to each element. Here's how we can use it:
<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"] ]; $results = []; array_map(function($a, $b) use (&$results) { // Get the key for both arrays $key = current(array_keys($a)); $a[$key] = ['ip' => $a[$key]]; $key = current(array_keys($b)); $b[$key] = ['name' => $b[$key]]; $results += array_merge_recursive($a, $b); }, $array1, $array2);</code>
How It Works:
Output:
var_dump($results);
Will produce the following output:
<code class="php">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)</code>
This solution effectively merges the two arrays while preserving the shared keys and ensuring the desired array structure.
The above is the detailed content of How to Merge PHP Arrays with Shared Keys Using `array_map`?. For more information, please follow other related articles on the PHP Chinese website!