Home  >  Article  >  Backend Development  >  How to Merge PHP Arrays with Shared Keys Using `array_map`?

How to Merge PHP Arrays with Shared Keys Using `array_map`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 07:21:30358browse

How to Merge PHP Arrays with Shared Keys Using  `array_map`?

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:

  • The callback function iterates through each element in $array1 and $array2.
  • For each element, it retrieves the key (e.g., "Camera1") and modifies the value accordingly, adding new keys ('ip' and 'name') to ensure consistent array structure.
  • The modified elements are merged using array_merge_recursive and stored in $results.
  • The resulting array combines both element values for each shared key, retaining the modified structure.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn