如何根据键合并两个PHP数组?array_merge覆盖问题求解决
Hey there, I totally get why array_merge() isn't working for you here—since both arrays share identical string keys, array_merge() will overwrite the values from the first array with those from the second, which is exactly what you don't want.
Let's fix this by building a custom solution that concatenates values based on matching keys. Here's how you can do it:
Step 1: Define Your Original Arrays
First, let's make sure your arrays are properly formatted (I've cleaned up the syntax a bit for clarity):
$Record1 = [ '647242M40642NGG916' => '647242|M40642NGG916|10', '647242M40725NG6621' => '647242|M40725NG6621|11', '647242M40732NG0287' => '647242|M40732NG0287|11', '647242M90830FYIF18' => '647242|M90830FYIF18|10', '647242M91221EXDU57' => '647242|M91221EXDU57|11', '647242M91304EX8878' => '647242|M91304EX8878|10' ]; $Record2 = [ '647242M40642NGG916' => '|96', '647242M40725NG6621' => '|95', '647242M40732NG0287' => '|99', '647242M90830FYIF18' => '|93', '647242M91221EXDU57' => '|99', '647242M91304EX8878' => '|92' ];
Step 2: Custom Merge with Value Concatenation
We'll use a foreach loop to iterate through the first array, then check if the same key exists in the second array. If it does, we'll concatenate the values; if not, we'll keep the original value from the first array (this adds a bit of safety in case keys are missing):
$Record3 = []; foreach ($Record1 as $key => $value) { // Check if the key exists in Record2 to avoid undefined index warnings if (isset($Record2[$key])) { $Record3[$key] = $value . $Record2[$key]; } else { $Record3[$key] = $value; } } // Output the result print_r($Record3);
What This Does
This code will produce exactly the $Record3 you're looking for:
Array ( [647242M40642NGG916] => 647242|M40642NGG916|10|96 [647242M40725NG6621] => 647242|M40725NG6621|11|95 [647242M40732NG0287] => 647242|M40732NG0287|11|99 [647242M90830FYIF18] => 647242|M90830FYIF18|10|93 [647242M91221EXDU57] => 647242|M91221EXDU57|11|99 [647242M91304EX8878] => 647242|M91304EX8878|10|92 )
Alternative: Using array_map (More Functional Style)
If you prefer a shorter, functional approach, you can use array_map with array_keys:
$keys = array_keys($Record1); $Record3 = array_combine( $keys, array_map(function($key) use ($Record1, $Record2) { return $Record1[$key] . (isset($Record2[$key]) ? $Record2[$key] : ''); }, $keys) );
This achieves the same result but uses array functions instead of a loop—choose whichever fits your coding style better!
内容的提问来源于stack exchange,提问作者JOSE0219

