Home > Backend Development > PHP Tutorial > How Can I Efficiently Merge Two 2D PHP Arrays Based on a Shared Column Using Native Functions?

How Can I Efficiently Merge Two 2D PHP Arrays Based on a Shared Column Using Native Functions?

Susan Sarandon
Release: 2024-12-03 22:10:14
Original
679 people have browsed it

How Can I Efficiently Merge Two 2D PHP Arrays Based on a Shared Column Using Native Functions?

Efficiently Merging 2D Arrays Based on Shared Column Values Using Native PHP Functions

Merging multiple arrays efficiently is a common task in PHP programming. This article explores an optimal solution for merging two 2D arrays based on a shared column value without resorting to nested loops or complex procedures.

Given two sample arrays:

$array1 = [
    ['rank' => '579', 'id' => '1'],
    ['rank' => '251', 'id' => '2'],
];

$array2 = [
    ['size' => 'S', 'status' => 'A', 'id' => '1'],
    ['size' => 'L', 'status' => 'A', 'id' => '2'],
];
Copy after login

The goal is to merge these arrays into a new array that combines the values from each array based on the matching id values:

$mergedArray = [
    ['size' => 'S', 'status' => 'A', 'id' => '1', 'rank' => '579'],
    ['size' => 'L', 'status' => 'A', 'id' => '2', 'rank' => '251'],
];
Copy after login

Utilizing Native PHP Array Functions

To facilitate this merging process, PHP provides two native functions:

  • array_merge_recursive(): Merges two arrays recursively, preserving the multidimensional structure.
  • my_array_merge(): A custom function that loops through the arrays and merges corresponding values.

Example Code Using array_merge_recursive():

$mergedArray = array_merge_recursive($array1, $array2);
Copy after login

Example Code Using my_array_merge():

function my_array_merge(array &$array1, array &$array2) {
    $result = [];
    foreach ($array1 as $key => &$value) {
        $result[$key] = array_merge($value, $array2[$key]);
    }
    return $result;
}

$mergedArray = my_array_merge($array1, $array2);
Copy after login

Both methods effectively merge the two arrays, producing the desired output. The choice of function depends on the specific performance requirements and code clarity preferences of the developer.

The above is the detailed content of How Can I Efficiently Merge Two 2D PHP Arrays Based on a Shared Column Using Native Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template