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:
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:
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!