Home > Backend Development > PHP Tutorial > How to Merge Arrays with Different Keys and Values in PHP?

How to Merge Arrays with Different Keys and Values in PHP?

Susan Sarandon
Release: 2024-12-31 13:07:12
Original
927 people have browsed it

How to Merge Arrays with Different Keys and Values in PHP?

Merge Row Data from Multiple Arrays

Merging data from multiple arrays can be a common requirement when working with complex data structures. This task becomes more challenging when the arrays have different keys and values.

To merge two arrays while retaining the original keys and values, you can use the array_merge_recursive function. This function recursively merges the elements of the input arrays. However, it requires the arrays to have string keys in order to be correctly merged.

Let's consider the example provided in the question:

$ar1 = [
    ['gross_value' => '100', 'quantity' => '1'],
    ['gross_value' => '200', 'quantity' => '1']
];

$ar2 = [
    ['item_title_id' => '1', 'order_id' => '4'],
    ['item_title_id' => '2', 'order_id' => '4']
];
Copy after login

To merge these arrays using array_merge_recursive, we need to first ensure that all the numeric keys are converted to strings. This can be done using the array_map function:

$ar1 = array_map('strval', $ar1);
$ar2 = array_map('strval', $ar2);
Copy after login

Now, we can use array_merge_recursive to merge the arrays:

$result = array_merge_recursive($ar1, $ar2);
Copy after login

The resulting $result array will have the desired structure:

[
    [
        'gross_value' => '100',
        'quantity' => '1',
        'item_title_id' => '1',
        'order_id' => 4
    ],
    [
        'gross_value' => '200',
        'quantity' => '1',
        'item_title_id' => '2',
        'order_id' => 4
    ]
]
Copy after login

The above is the detailed content of How to Merge Arrays with Different Keys and Values in PHP?. 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