Home > Backend Development > PHP Tutorial > How to Merge Two Arrays with Key-Value Pairs into a Single Array in PHP?

How to Merge Two Arrays with Key-Value Pairs into a Single Array in PHP?

Susan Sarandon
Release: 2024-12-15 07:17:10
Original
671 people have browsed it

How to Merge Two Arrays with Key-Value Pairs into a Single Array in PHP?

Merging Row Data from Multiple Arrays

Merging data from multiple arrays into a single cohesive structure can be a common programming task. This question explores a scenario where two arrays need to be merged to produce a new array with specific attributes.

The first array contains two elements, each consisting of a "gross_value" and a "quantity" key-value pair. The second array also contains two elements, each consisting of an "item_title_id" and an "order_id" key-value pair.

The goal is to merge these arrays into a new array where each element combines all the key-value pairs from both original arrays. The resulting array should have four key-value pairs: "gross_value," "quantity," "item_title_id," and "order_id."

Solution

The recommended approach to achieve this merging is through the use of the array_merge_recursive function. This function takes multiple arrays as input and recursively merges their values.

To prepare for merging, the numeric keys of both arrays are converted to strings, ensuring they become associative arrays. The following code demonstrates this:

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

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

After converting the arrays, they can be merged using array_merge_recursive:

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

This code will merge the key-value pairs from both arrays, producing the desired result:

[
    ['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 Two Arrays with Key-Value Pairs 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