Home >Backend Development >PHP Tutorial >How to Merge PHP Arrays with Matching Keys and Create Sub-Arrays?

How to Merge PHP Arrays with Matching Keys and Create Sub-Arrays?

DDD
DDDOriginal
2024-10-27 20:33:301061browse

How to Merge PHP Arrays with Matching Keys and Create Sub-Arrays?

PHP Array Merge: Combining Arrays with Matching Keys

This question explores how to merge two PHP arrays that share the same keys. Let's dive into the problem and solution.

Problem:

Consider the following two arrays:

  • First Array: Key-value pairs with keys representing camera numbers and values representing IP addresses.
  • Second Array: Key-value pairs with the same camera numbers but different values representing camera names.

The objective is to merge these arrays by aggregating the values corresponding to each matching key.

Solution Using array_map:

While array_merge_recursive can merge arrays recursively, it requires arrays with matching key-value pairs. A custom solution using array_map can achieve the desired result:

$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);

Explanation:

  • For each key in the first array, it creates a sub-array with a key 'ip' and value set to the original value.
  • Similarly, for each key in the second array, it creates a sub-array with a key 'name' and value set to the original value.
  • Finally, it uses array_merge_recursive to merge the sub-arrays sharing the same camera number.

The output is an array with keys representing camera numbers and values as sub-arrays containing 'ip' and 'name' properties.

By leveraging array_map and custom key manipulation, this solution efficiently merges arrays with matching keys while still preserving the key-value structure.

The above is the detailed content of How to Merge PHP Arrays with Matching Keys and Create Sub-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