Home >Backend Development >PHP Tutorial >How Can I Merge Two 2D Arrays in PHP Based on a Shared Column Value?
In the realm of data manipulation, merging arrays often emerges as a common task. This article explores a specific scenario: combining two 2D arrays based on a shared column value.
Imagine two arrays, each containing objects with common identifiers. These arrays might look something like this:
$array1 = [ ['rank' => '579', 'id' => '1'], ['rank' => '251', 'id' => '2'], ]; $array2 = [ ['size' => 'S', 'status' => 'A', 'id' => '1'], ['size' => 'L', 'status' => 'A', 'id' => '2'], ];
Our goal is to merge these arrays into a single array, combining the elements that share the same 'id' value.
PHP offers several functions that facilitate array merging. Let's explore them:
1. array_merge_recursive(): This function combines arrays recursively, overwriting existing keys in the target array with values from the source array. It effortlessly achieves the desired merging, as seen in the following code:
$mergedArray = array_merge_recursive($array1, $array2);
2. Custom Merging Function: For maximum control, we can create a custom merging function:
function my_array_merge(&$array1, &$array2) { $result = []; foreach ($array1 as $key => &$value) { $result[$key] = array_merge($value, $array2[$key]); } return $result; }
This function iterates over the arrays, merging the corresponding elements based on their keys.
Combining 2D arrays by shared column values is a common operation. PHP provides native functions like array_merge_recursive() for quick merging. However, for customized merging or performance optimization, custom functions can be employed. The choice of approach depends on the specific requirements and desired control.
The above is the detailed content of How Can I Merge Two 2D Arrays in PHP Based on a Shared Column Value?. For more information, please follow other related articles on the PHP Chinese website!