Home > Backend Development > PHP Tutorial > 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
Release: 2024-10-29 13:33:02
Original
668 people have browsed it

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>
Copy after login

Array 2:

<code class="php">array(
    [
        "Camera1" => "VT"
    ],
    [
        "Camera2" => "UB"
    ],
    [
        "Camera3" => "FX"
    ]
)</code>
Copy after login

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>
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template