Home >Backend Development >PHP Tutorial >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'] ];
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 ] ]
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);
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!