PHP to combine multiple arrays into an array of methods and instance code

  • 2020-03-31 21:31:47
  • OfStack

1. Merge arrays
The array_merge() function merges the arrays together, returning an associated array. The resulting array begins with the first input array parameter, and is forced in the order in which the array parameters appear. Its form is:
 
array array_merge (array array1 array2 ... ,arrayN) 

Merges the elements of one or more arrays, with the values in one array appended to the previous array. Returns the array as the result.
If the input array has the same string key name, the value following that key name overrides the previous value. However, if the array contains a numeric key name, the subsequent value will not override the original value, but will be appended to it.
If only one array is given and the array is numerically indexed, the key name is continuously reindexed.
Examples are as follows:
 
$face = array("J","Q","K","A"); 
$numbered = array("2","3","4","5","6","7","8","9"); 
$cards = array_merge($face, $numbered); 
shuffle($cards); 
print_r($cards); 

This will return the results shown below to run the code:
 
Array ( [0] => A [1] => 4 [2] => 9 [3] => 3 [4] => K [5] => 7 [6] => 5 [7] => Q [8] => 6 [9] => 8 [10] => 2 [11] => J ) 

Recursively append arrays
The array_merge_recursive() function, like array_merge(), merges two or more arrays together to form an associative array. The difference between the two is that the function takes a different approach when a key in an input array already exists in the result array. Array_merge () overrides the previously existing key/value pair and replaces it with the key/value pair in the current input array, while array_merge_recursive() merges the two values together to form a new array with the original key as the array name. There is another form of array merging, which is recursively appending an array. Its form is:
The view sourceprint? Array array_merge_recursive(array key,array values)

Here's an example:
 
$class1 = array("John" => 100, "James" => 85); 
$class2 = array("Micky" => 78, "John" => 45); 
$classScores = array_merge_recursive($class1, $class2); 
print_r($classScores); 

This will return the following results:
The view sourceprint? Array ([John] = > Array ([0] = > 100 [1] = > 45) [James] = > 85 [Micky] = > 78).

3. Join two arrays
The array_combine() function gets a new array of committed keys and corresponding values. Its form is:
The view sourceprint? Array array_merge(array array1,array array2[... array arrayN])

Note that the two input arrays must be the same size and cannot be empty. Here's an example:
 
$abbreviations = array("AL","AK","AZ","AR"); 
$states = array("Alabama","Alaska","Arizona","Arkansas"); 
$stateMap = array_combine($abbreviations,$states); 
print_r($stateMap); 

This returns:
 
Array ( [AL] => Alabama [AK] => Alaska [AZ] => Arizona [AR] => Arkansas ) 

Related articles: