Home > Backend Development > PHP Tutorial > How Can I Merge Multiple Arrays with Different Keys into a Single Array in PHP?

How Can I Merge Multiple Arrays with Different Keys into a Single Array in PHP?

Linda Hamilton
Release: 2024-12-28 18:12:11
Original
584 people have browsed it

How Can I Merge Multiple Arrays with Different Keys into a Single Array in PHP?

Combining Row Data from Multiple Arrays

In an effort to consolidate data from different arrays, a user recently encountered a challenge in merging the contents into a desired format. The arrays in question contain details such as gross value, quantity, item title ID, and order ID, as follows:

Array 1:
[
    ['gross_value' => '100', 'quantity' => '1'],
    ['gross_value' => '200', 'quantity' => '1']
]

Array 2:
[
    ['item_title_id' => '1', 'order_id' => '4'],
    ['item_title_id' => '2', 'order_id' => '4']
];
Copy after login

The intended result is a merged array with all the fields combined, resembling the following:

Merged Array:
[
    [
        '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

To address this challenge, a solution was suggested using the array_merge_recursive function. This function allows for the effective combination of associative arrays, ensuring that duplicate keys are properly merged. By converting all numeric keys to strings, the arrays become associative, making them compatible for merging.

The code snippet provided below demonstrates the application of this solution:

$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']];

$result = array_merge_recursive($ar1, $ar2);

print_r($result);
Copy after login

When executed, the code yields the desired merged array format, as specified in the problem statement.

The above is the detailed content of How Can I Merge Multiple Arrays with Different Keys into a Single Array 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