Merging Data from Multiple Arrays for Row-Based Structures
In data manipulation tasks, it is often necessary to combine data from disparate sources to create a comprehensive dataset. This can be achieved by merging data from multiple arrays. Specifically, when the goal is to construct row-based structures, the array_merge_recursive function offers a powerful solution.
Consider the following example. Two arrays are given with the following structures:
Array 1:
Array 2:
The objective is to merge the contents of these arrays into a single array with the following structure:
To accomplish this, the array_merge_recursive function can be employed. This function recursively merges arrays, combining values with the same keys into nested arrays. However, in the given context, the arrays have numeric keys. For array_merge_recursive to work correctly, all numeric keys must be converted to strings (associative array).
The following code snippet demonstrates the 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'] ]; // Convert numeric keys to strings foreach ($ar1 as &$row) { $row = array_combine(array_keys($row), array_values($row)); } foreach ($ar2 as &$row) { $row = array_combine(array_keys($row), array_values($row)); } // Merge arrays $result = array_merge_recursive($ar1, $ar2); print_r($result);
Executing this code will produce the desired merged array, where the data from both arrays are combined into a single row-based structure.
The above is the detailed content of How Can I Merge Multiple Arrays into a Single Row-Based Structure in PHP?. For more information, please follow other related articles on the PHP Chinese website!