基于year列合并两个数组并整合对应字段的技术问询
Solution to Merge Arrays by Year in PHP
Here's a clean and efficient way to merge your two arrays based on the year column, combining corresponding fields and including all years from both datasets:
Step-by-Step Explanation
- Create Lookup Arrays: Convert both input arrays into associative arrays where keys are
yearvalues. This lets us quickly accessvoucherandsamplevalues without slow nested loops. - Collect Unique Years: Gather all distinct years from both lookup arrays to ensure no entries are missed.
- Build Merged Array: For each unique year, construct an entry that includes the year, plus the
voucher(if present) andsample(if present).
Code Implementation
// Your original arrays $array1 = [ ['year' => 2016, 'voucher' => 7], ['year' => 2017, 'voucher' => 9], ['year' => 2018, 'voucher' => 6], ['year' => 2015, 'voucher' => 1], ['year' => 2014, 'voucher' => 2] ]; $array2 = [ ['year' => 2018, 'sample' => 4], ['year' => 2017, 'sample' => 3], ['year' => 2019, 'sample' => 5] // Example of a year only in array2 ]; // Create lookup arrays for quick value access $voucherLookup = array_column($array1, 'voucher', 'year'); $sampleLookup = array_column($array2, 'sample', 'year'); // Get all unique years from both datasets $allYears = array_unique(array_merge(array_keys($voucherLookup), array_keys($sampleLookup))); sort($allYears); // Optional: Sort years chronologically // Build the merged array $mergedArray = []; foreach ($allYears as $year) { $mergedArray[] = [ 'year' => $year, 'voucher' => $voucherLookup[$year] ?? null, // Use null if voucher doesn't exist 'sample' => $sampleLookup[$year] ?? null // Use null if sample doesn't exist ]; } // Output the result print_r($mergedArray);
Example Output
Array ( [0] => Array ( [year] => 2014 [voucher] => 2 [sample] => ) [1] => Array ( [year] => 2015 [voucher] => 1 [sample] => ) [2] => Array ( [year] => 2016 [voucher] => 7 [sample] => ) [3] => Array ( [year] => 2017 [voucher] => 9 [sample] => 3 ) [4] => Array ( [year] => 2018 [voucher] => 6 [sample] => 4 ) [5] => Array ( [year] => 2019 [voucher] => [sample] => 5 ) )
Customization Tips
- If you prefer
0instead ofnullfor missing values, replace?? nullwith?? 0. - Remove the
sort($allYears)line if you don't need the merged array to be in chronological order. - This approach is efficient even for large arrays, as it avoids nested loops and uses O(n + m) time complexity.
内容的提问来源于stack exchange,提问作者Hem's Gurjar
相关产品推荐
相关产品推荐

