Merging JSON Arrays by Key in PHP
Merging two JSON structures based on a shared identifier is a common requirement when working with API responses or configuration files. In your specific case, you are joining metadata about column definitions with their default values using COLUMN_NAME as the join key. While this looks like a standard relational join, implementing it in PHP requires careful handling of array indices and data types to avoid collisions or silent data loss.
The most robust approach involves decoding both JSON strings into associative arrays in memory, iterating through one array to establish an index map, and then populating the final result set. This method ensures that even if the input arrays are not perfectly ordered, the merge logic remains deterministic.
Decoding and Indexing
First, you must parse the raw JSON strings using json_decode. Crucially, you need to pass the second argument as true to get an associative array rather than a numerically indexed one. This allows you to access elements by their keys (e.g., COLUMN_NAME) directly.
$jsonString1 = '[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number"},{"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number"}]';
$jsonString2 = '[{"COLUMN_NAME":"ORDER_NO","DEFAULT_VALUE":"1521"},{"COLUMN_NAME":"CUSTOMER_NO","DEFAULT_VALUEE":"C1435"}]';
$data1 = json_decode($jsonString1, true);
$data2 = json_decode($jsonString2, true);
Once decoded, you should transform the first dataset into an associative array where the join key (COLUMN_NAME) is the index. This acts as a lookup table for the second dataset.
$lookup = [];
foreach ($data1 as $item) {
$lookup[$item['COLUMN_NAME']] = $item;
}
Performing the Merge
With the lookup map ready, you can iterate through the second array. For every item in data2, check if its COLUMN_NAME exists in your $lookup table. If it does, you merge the properties from $lookup[$key] into the current item from data2.
This approach naturally handles the structure change you mentioned is acceptable. By merging properties, you effectively create a wide table where each row corresponds to a unique column name. Note that if COLUMN_NAME appears multiple times in your source JSON, this simple merge will overwrite previous entries. In production environments, you would typically validate for duplicates or use an array of values to prevent data loss.
$merged = [];
foreach ($data2 as $item) {
$key = $item['COLUMN_NAME'];
if (isset($lookup[$key])) {
// Merge properties from the first JSON into the second
$mergedItem = array_merge($item, $lookup[$key]);
$merged[] = $encodedItem; // Assuming you want to encode immediately or keep as array
} else {
// Handle case where COLUMN_NAME exists in metadata but not defaults (or vice versa)
// You might choose to skip or throw an error depending on requirements
$merged[] = $item;
}
}
Handling Property Collisions and Naming
In your example, the first JSON uses COLUMN_TITLE while the second uses DEFAULT_VALUE. Since these keys are unique across both sets, a simple array_merge works perfectly. However, if both JSONs contained a key named ID, array_merge would overwrite the value from the second array with the one from the first (since PHP arrays are ordered). If you need to preserve all values in case of collisions, you should manually handle the merge logic or use + operator for specific fields.
Additionally, notice the typo in your second JSON snippet: "DEFAULT_VALUEE". When merging data from external sources or APIs, strict validation is often required. You might want to normalize keys before merging to ensure consistency across your application's state.
Serialization Back to JSON
Once the merge logic is complete and you have an array of associative arrays representing the combined data, convert it back to a JSON string using json_encode. This output matches your desired structure where every row contains both the title and the default value.
$jsonEncoded = json_encode($merged);
// Output: [{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number","DEFAULT_VALUE":"1521"},...]
Why This Approach Works
Using a lookup map is generally more efficient than nested loops ($O(n^2)$) because it reduces the complexity to linear time ($O(n)$). It also decouples the order of input arrays from the output order, ensuring that the result is driven by the integrity of the join key rather than the sequence of data arrival. If you are working within a Laravel application, consider using Eloquent relationships or collection helpers if the data resides in database tables, but for pure JSON manipulation, this procedural method offers maximum control and minimal overhead.