PHP中array_merge()和array_combine()函数的区别
array_merge()函数: array_merge()函数用于将两个或多个数组合并为一个数组。此函数用于将两个或多个数组的元素或值合并到一个数组中。合并以这样一种方式发生,即一个数组的值被附加到前一个数组的末尾。该函数将以逗号分隔的数组列表作为需要合并的参数,并返回一个新数组,其中包含传入参数的数组的合并值。
句法:
array array_merge( $array1, $array2, ...., $array n)
其中,$array1,$array2,。 . .是需要合并的输入数组。
示例:合并两个数组的PHP程序。
PHP
"Python","subject2" => "sql");
// Define array2 with keys and values
$array2 = array("subject3" => "c/c++","subject4" => "java");
// Merge both array1 and array2
$final = array_merge($array1, $array2);
// Display merged array
print_r($final);
?>
PHP
"Python", "subject2" => "sql");
// Define array2 with keys and values
$array2 = array("subject3" => "c/c++", "subject4" => "java");
// Define array3 with keys and values
$array3 = array("subject5" => "CN", "subject6" => "OS");
// Define array4 with keys and values
$array4 = array("subject7" => "data mining", "subject8" => "C#");
// Merge all arrays
$final = array_merge($array1, $array2, $array3, $array4);
// Display merged array
print_r($final);
?>
PHP
PHP
Array
(
[subject1] => Python
[subject2] => sql
[subject3] => c/c++
[subject4] => java
)
示例 2:合并多个数组的PHP程序。
PHP
"Python", "subject2" => "sql");
// Define array2 with keys and values
$array2 = array("subject3" => "c/c++", "subject4" => "java");
// Define array3 with keys and values
$array3 = array("subject5" => "CN", "subject6" => "OS");
// Define array4 with keys and values
$array4 = array("subject7" => "data mining", "subject8" => "C#");
// Merge all arrays
$final = array_merge($array1, $array2, $array3, $array4);
// Display merged array
print_r($final);
?>
Array
(
[subject1] => Python
[subject2] => sql
[subject3] => c/c++
[subject4] => java
[subject5] => CN
[subject6] => OS
[subject7] => data mining
[subject8] => C#
)
array_combine()函数: array_combine()函数用于组合两个数组并创建一个新数组,其中一个数组作为键,另一个数组作为值,即一个数组的所有元素将是新数组的键,所有元素都是第二个数组将是这个新数组的值。
语法:
array_combine(array1, array2)
其中,array1 是第一个带有键的数组,array2 是第二个带有值的数组。
示例:用于组合数组的PHP程序。
PHP
Array
(
[subject1] => c/c++
[subject2] => java
)
示例 2:
PHP
Array
(
[subject1] => c/c++
[subject2] => java
[subject3] => Python
[subject4] => HTML
)
array_merge() 和 array_combine()函数之间的区别: array_merge() Function array_combine() FunctionThis function merges the two or more arrays. This array combine only two arrays. This function merges the arrays such that all the arrays have keys and values. This function combine the one array containing keys and another array containing values. The arrays are appended at the end of the first array. The arrays are combined.