Home > Article > Backend Development > How to combine multiple arrays into one multidimensional array in PHP
How to merge multiple arrays into a multi-dimensional array in PHP
In PHP development, we often encounter the need to merge multiple arrays into a multi-dimensional array. This operation is very useful when operating large data collections and can help us better organize and process data. This article will introduce you to several common methods to achieve this operation, and attach code examples for reference.
Method 1: Use the array_merge function
The array_merge function is a commonly used array merging function in PHP. It can merge multiple arrays into a new array one by one. We can merge arrays one by one through loop traversal to achieve merging of multi-dimensional arrays.
<?php $array1 = array('a' => 1, 'b' => 2); $array2 = array('c' => 3, 'd' => 4); $array3 = array('e' => 5, 'f' => 6); $result = array_merge($array1, $array2, $array3); print_r($result); ?>
The above code will output the following results:
Array
(
[a] => 1 [b] => 2 [c] => 3 [d] => 4 [e] => 5 [f] => 6
)
Method 2: Use the " " operator
In PHP, we can use the " " operator to merge multiple arrays into one array. This method is relatively concise, but there is one caveat: if there are elements with the same key name in the two arrays, only the elements in the first array will be retained in the merged array.
<?php $array1 = array('a' => 1, 'b' => 2); $array2 = array('b' => 3, 'c' => 4); $array3 = array('c' => 5, 'd' => 6); $result = $array1 + $array2 + $array3; print_r($result); ?>
The above code will output the following results:
Array
(
[a] => 1 [b] => 2 [c] => 4 [d] => 6
)
Method 3: Use array_replace_recursive function
If you The arrays that need to be merged are multi-dimensional arrays, and we can use the array_replace_recursive function to merge them. This function recursively merges the values of the arrays and returns a new merged array.
<?php $array1 = array('a' => array('b' => 1, 'c' => 2)); $array2 = array('a' => array('c' => 3, 'd' => 4)); $array3 = array('a' => array('d' => 5, 'e' => 6)); $result = array_replace_recursive($array1, $array2, $array3); print_r($result); ?>
The above code will output the following results:
Array
(
[a] => Array ( [b] => 1 [c] => 3 [d] => 5 [e] => 6 )
)
Summary:
This article introduces three commonly used Method to merge multiple arrays into a multi-dimensional array. You can choose the appropriate method according to your own needs and merge multi-dimensional arrays through the array_merge function, " " operator or array_replace_recursive function. These methods are very useful when dealing with large data collections and can help us better organize and process the data. Hope this article is helpful to you!
The above is the detailed content of How to combine multiple arrays into one multidimensional array in PHP. For more information, please follow other related articles on the PHP Chinese website!