Home >Backend Development >PHP Tutorial >How to Efficiently Merge Two 2D Arrays Based on a Shared Column Value in PHP?

How to Efficiently Merge Two 2D Arrays Based on a Shared Column Value in PHP?

DDD
DDDOriginal
2024-12-16 07:31:15456browse

How to Efficiently Merge Two 2D Arrays Based on a Shared Column Value in PHP?

Merging 2D Arrays Based on Shared Column Value

For the given 2D arrays:

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

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

Merging Using Native PHP Array Functions

To merge the arrays based on the shared 'id' column, you can leverage the array_merge_recursive() function. It recursively merges elements from the input arrays while preserving keys:

$merged = array_merge_recursive($array1, $array2);

print_r($merged);
// Output:
// Array
// (
//     [0] => Array
//         (
//             [rank] => 579
//             [id] => 1
//             [size] => S
//             [status] => A
//         )
//     [1] => Array
//         (
//             [rank] => 251
//             [id] => 2
//             [size] => L
//             [status] => A
//         )
// )

Custom Merging Function

Alternatively, you can define your own function for merging arrays based on a specified key:

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

$merged = my_array_merge($array1, $array2, 'id');

print_r($merged);
// Output:
// Array
// (
//     [1] => Array
//         (
//             [rank] => 579
//             [id] => 1
//             [size] => S
//             [status] => A
//         )
//     [2] => Array
//         (
//             [rank] => 251
//             [id] => 2
//             [size] => L
//             [status] => A
//         )
// )

Consider using my_array_merge() when working with large arrays as it can potentially outperform array_merge_recursive().

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

Statement:
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