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?

How can I merge two PHP arrays with matching keys into a single array, preserving the key-value pairs from both arrays?

DDD
DDDOriginal
2024-10-29 13:33:02627browse

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!

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
Previous article:PHP 8.2 ReleasedNext article:PHP 8.2 Released