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."
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);
After converting the arrays, they can be merged using array_merge_recursive:
$result = array_merge_recursive($ar1, $ar2); print_r($result);
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] ]
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!