Recursively merge two multidimensional associative arrays and define new subarray keys according to their origin array

Recursively merge two multidimensional associative arrays and define new subarray keys according to their origin array

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Merging Multidimensional Arrays by Key in PHP

You are attempting to consolidate two distinct data structures into a single, normalized format. The first array contains IP addresses nested within camera identifiers, while the second holds model names or status codes for those same devices. Your goal is to align these by their shared keys—Camera1, Camera2, and so on—and transform the structure from a list of associative sub-arrays into a flat associative array where each key maps to an object containing both ip and name.

Your current approach uses array_merge followed by nested loops. While array_merge is efficient for simple arrays, it behaves differently with multidimensional structures than you might expect. When merging multiple arrays of the same dimension (associative), PHP preserves keys but does not recursively merge sub-arrays; instead, it may overwrite values or maintain order based on implementation details depending on the specific versions and data types involved. More critically, your subsequent loop reconstructs a new array using array_push logic via $cam[], which ignores the original key structure entirely. This results in losing the association between cameras and their properties, effectively flattening the data into a list rather than preserving the hierarchical mapping you need.

To achieve the desired result—where each camera key directly points to an associative array with distinct property names—you need to iterate through one array and pull corresponding values from the other using the shared identifiers as indices. This pattern is common in ETL (Extract, Transform, Load) processes or when normalizing database query results into a specific DTO (Data Transfer Object) structure.

Here is a robust implementation that leverages array_column to extract values efficiently:

$array1 = [
    ["Camera1" => "192.168.101.71"],
    ["Camera2" => "192.168.101.72"],
    ["Camera3" => "192.168.101.74"],
];

$array2 = [
    ["Camera1" => "VT"],
    ["Camera2" => "UB"],
    ["Camera3" => "FX"]
];

// Extract the values for each key into a flat associative array
$ips = array_column($array1, null, 'Camera1'); // Adjusted logic needed below

Actually, array_column requires a specific structure to work seamlessly with your input format. Since your data is an array of arrays where the key exists inside the sub-array, we must first flatten or map these structures before merging them. The most readable and performant approach involves iterating over one array and indexing the other.

$result = [];

// Iterate through the first array to ensure we process in the correct order
foreach ($array1 as $subArray) {
    // Extract the camera identifier from the current sub-array
    foreach ($subArray as $camKey => $ipAddress) {
        // Locate the corresponding entry in the second array
        if (isset($array2[$camKey])) {
            // Retrieve the name associated with this camera
            $name = $array2[$camKey]['Camera1']; 
            // Note: The source material implies the key inside sub-array is always 'CameraX', 
            // but to be safe, we should access the value directly if the structure varies slightly.
            
            // However, looking at the source data strictly:
            // $array2[$camKey] returns an array like ['Camera1' => 'VT']
            // So we need to extract the value based on the dynamic key or assume a fixed inner key.
            
            // Let's refine the extraction logic for the specific structure provided:
            $name = reset($array2[$camKey]); 
        } else {
            // Handle missing data gracefully if necessary
            $name = null;
        }

        $result[$camKey] = [
            'ip' => $ipAddress,
            'name' => $name,
        ];
    }
}

A cleaner variation avoids the inner foreach if you know the key inside the sub-arrays is consistent. If the inner keys are always named after the camera sequence (e.g., 'Camera1', 'Camera2'), you can directly index the second array using the value from the first:

$result = [];
foreach ($array1 as $item) {
    foreach ($item as $camId => $ipAddr) {
        // Assuming the structure of $array2 matches $camId exactly
        if (isset($array2[$camId])) {
            $data = $array2[$camId];
            // Extract the value dynamically in case the inner key isn't fixed
            $name = reset($data); 
            
            $result[$camId] = [
                'ip' => $ipAddr,
                'name' => $name,
            ];
        }
    }
}

This approach guarantees that the final array maintains the top-level keys (Camera1, Camera2) and populates them with the merged data. It avoids the pitfalls of array_merge in multidimensional contexts and ensures that missing keys in one array do not corrupt the other. If you are working within a Laravel application, consider mapping this result into an Eloquent model or casting it to a DTO using collect($result) and map operations for further type safety before rendering views.

Our network