Merging 2D Arrays by Shared Column Value in PHP
Merging two multidimensional arrays based on a shared key is a frequent requirement when consolidating data from different sources, such as joining product attributes with inventory levels or combining user profiles with activity logs. While iterating through one array and searching the other works, it often leads to nested loops that degrade performance quadratically ($O(n^2)$). For larger datasets, this approach becomes prohibitively slow. The goal is to achieve a merge using native PHP functions that maintains linear time complexity ($O(n)$) while keeping the code readable and efficient.
The core strategy relies on transforming one array into an associative lookup table. By converting the second array into a structure where the shared key (e.g., id) acts as the index, you reduce the lookup operation from a search through an indexed list to a direct array access. PHP's array_column function is ideal for this transformation. It extracts a column of values from a multidimensional array and returns it as a single-dimensional array.
Here is how you can structure the solution using native functions:
$listA = [
['rank' => '579', 'id' => '1'],
['rank' => '251', 'id' => '2'],
];
$listB = [
['size' => 'S', 'status' => 'A', 'id' => '1'],
['size' => 'L', 'status' => 'A', 'id' => '2'],
];
// Create an associative array where 'id' is the key
$lookup = array_column($listB, null, 'id');
// Merge by iterating over the first list and adding values from the lookup
$result = [];
foreach ($listA as $item) {
$itemId = $item['id'];
// Check if the ID exists in our lookup table
if (isset($lookup[$itemId])) {
$mergedItem = $item + $lookup[$itemId];
// Reorder keys to ensure 'size' and 'status' appear before 'rank' if desired
$result[] = array_merge($lookup[$itemId], $item);
}
}
print_r($result);
In this implementation, array_column builds a map like ['1' => ['size' => 'S', ...], '2' => ['size' => 'L', ...]]. This step runs in linear time relative to the size of $listB. The subsequent foreach loop iterates over $listA, performing constant-time lookups for each item. Consequently, the total complexity remains linear ($O(n + m)$), which is significantly more efficient than nested loops.
However, there are specific trade-offs to consider regarding key order and data integrity. The + operator in PHP performs a shallow merge where keys from the left operand overwrite those on the right if they share the same name. In the example above, we explicitly reorder using array_merge to place the attributes from $listB first. This ensures that if both arrays contained an id key (which they do), or any other potential collision, the intended source takes precedence. If you prefer strict overwriting where $listA values take priority regardless of order, you would simply use $item + $lookup[$itemId].
It is also worth noting that using string keys for IDs, as shown in your example ('1', '2'), aligns perfectly with PHP's behavior. If your data used integer IDs (e.g., 1, 2 without quotes), array_column would still work seamlessly, but you must ensure the types match exactly between the two source arrays to avoid silent failures where a string key fails to match an integer key.
For projects built on the Laravel framework, this pattern can be abstracted further using Eloquent relationships or collection helpers like mergeWith, but the underlying logic of building an index remains consistent across both vanilla PHP and the framework's collection system. Understanding these native mechanics helps you write more performant code even when leveraging high-level abstractions.