How to merge PHP arrays with matching keys and combine their values?

DDD
Release: 2024-11-01 08:28:30
Original
282 people have browsed it

How to merge PHP arrays with matching keys and combine their values?

PHP Array: Merging Arrays with Matching Keys

In PHP, there are instances when we need to merge multiple arrays, ensuring that items with the same key are combined. Consider the following scenario:

Problem:

We have two arrays with matching keys and wish to merge them, such as:

<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']
];</code>
Copy after login

Solution:

To merge these arrays while preserving the key-value relationship, we can use array_map in conjunction with array_keys to manipulate and combine them:

<code class="php">$results = array();

array_map(function($a, $b) use (&$results) {

    $key1 = current(array_keys($a));
    $a[$key1] = ['ip' => $a[$key1]];

    $key2 = current(array_keys($b));
    $b[$key2] = ['name' => $b[$key2]];

    $results = array_merge_recursive($a, $b);

}, $array1, $array2);</code>
Copy after login

This solution works by looping through each element in both arrays, extracting the corresponding key, and renaming the values to ensure they can be merged using array_merge_recursive. The result is an array where each key has a merged result, as shown below:

<code class="php">array (
  'Camera1' => array (
    'ip' => '192.168.101.71',
    'name' => 'VT'
  ),
  'Camera2' => array (
    'ip' => '192.168.101.72',
    'name' => 'UB'
  ),
  'Camera3' => array (
    'ip' => '192.168.101.74',
    'name' => 'FX'
  )
)</code>
Copy after login

The above is the detailed content of How to merge PHP arrays with matching keys and combine their values?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!