array_merge() - 合并一个或多个数组 - php 数组函数
array_merge()
(PHP 4, PHP 5, PHP 7)
合并一个或多个数组
说明
array_merge(array $array1[,array $...]): arrayarray_merge()将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。
如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。
如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。
参数
$array1要合并的第一个数组。
要合并的数组列表。
返回值
返回结果数组。
范例
Example #1array_merge()例子
以上例程会输出:
Array ( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4 )
Simplearray_merge()例子
别忘了数字键名将会被重新编号!
Array ( [0] => data )
如果你想完全保留原有数组并只想新的数组附加到后面,用+运算符:
第一个数组的键名将会被保留。在两个数组中存在相同的键名时,第一个数组中的同键名的元素将会被保留,第二个数组中的元素将会被忽略
array(5) { [0]=> string(6) "zero_a" [2]=> string(5) "two_a" [3]=> string(7) "three_a" [1]=> string(5) "one_b" [4]=> string(6) "four_b" }
Example #3array_merge()合并非数组的类型
以上例程会输出:
Array ( [0] => foo [1] => bar )
参见
array_merge_recursive()
递归地合并一个或多个数组array_replace()
使用传递的数组替换第一个数组的元素array_combine()
创建一个数组,用一个数组的值作为其键名,另一个数组的值作为其值- array operators
In some situations, the union operator ( + ) might be more useful to you than array_merge. The array_merge function does not preserve numeric key values. If you need to preserve the numeric keys, then using + will do that. ie: Note the implicit "array_unique" that gets applied as well. In some situations where your numeric keys matter, this behaviour could be useful, and better than array_merge. --Julian
As PHP 5.6 you can use array_merge + "splat" operator to reduce a bidimensonal array to a simple array: PHPAn addition to what Julian Egelstaff above wrote - the array union operation (+) is not doing an array_unique - it will just not use the keys that are already defined in the left array. The difference between union and merge can be seen in an example like this:if you generate form select from an array, you probably want to keep your array keys and order intact, if so you can use ArrayMergeKeepKeys(), works just like array_merge : array ArrayMergeKeepKeys ( array array1 [, array array2 [, array ...]]) but keeps the keys even if of numeric kind. enjoyAs PHP 5.6 you can use array_merge + "splat" operator to reduce a bidimensonal array to a simple array:to get unique value from multi dimensional array use this instead of array_unique(), because array_unique() does not work on multidimensional: array_map("unserialize", array_unique(array_map("serialize", $array))); Hope this will help someone; Example $a=array(array('1'),array('2'),array('3'),array('4)); $b=array(array('2'),array('4'),array('6'),array('8)); $c=array_merge($a,$b); then write this line to get unique values $c=array_map("unserialize", array_unique(array_map("serialize", $c))); print_r($c);Reiterating the notes about casting to arrays, be sure to cast if one of the arrays might be null: Produces: 1 ============== Array ( [0] => zzzz [1] => xxxx [2] => mmmm [3] => nnnn ) 2 ============== Array ( [0] => zzzz [1] => xxxx ) 3 ============== 4 ============== Array ( [0] => zzzz [1] => xxxx ) 5 ============== Result is nullI constantly forget the direction of array_merge so this is partially for me and partially for people like me. array_merge is a non-referential non-inplace right-reduction. For different ctrl-f typers, it's reduce-right, side-effect free, idempotent, and non in-place. ex: $a = array_merge(['k' => 'a'], ['k' => 'b']) => ['k' => 'b'] array_merge(['z' => 1], $a) => does not modify $a but returns ['k' => 'b', 'z' => 1]; Hopefully this helps people that constant look this up such as myself.I keep seeing posts for people looking for a function to replace numeric keys. No function is required for this, it is default behavior if the + operator: Array ( [1] => one [two] => 2 [3] => three [four] => 4 ) How this works: The + operator only adds unique keys to the resulting array. By making the replacements the first argument, they naturally always replace the keys from the second argument, numeric or not! =)Array merge will return null if any parameter not an array Here is function for solution of array_merge function copied from http://sdtuts.com/php-array_merge-function-issue/ Code example how to use itThis function merges any number of arrays and maintains the keys:Sometimes you need to modify an array with another one here is my approach to replace an array's content recursively with delete opiton. Here i used "::delete::" as reserved word to delete items.It is not officially documented but it is summarily important information for everyone to know: neither array_merge or array_merge_recursive functions will function correctly if non-array objects are used as parameters. You would probably expect these functions to ignore non-array elements, right? However, if one parameter is null it PHP will not only return null for the entire function but will also (not always) raise an error, such as : [ Warning: array_merge(): Argument #x is not an array... ] This error message won't appear if the defective variable is an empty array (an empty array is still an array), but it will result in an undesirable incomplete Array. There are several solutions for this problem by validating the Arrays before use them in these functions, but the most efficient way is to enforce the element as an array directly in the function itself. I.e.: $merged = array_merge( (array)$first_array, (array)$second_array );to merge arrays and preserve the key i found the following working with php 4.3.1: dont know if this is working with other php versions but it is a simple and fast way to solve that problem.It would seem that array_merge doesn't do anything when one array is empty (unset): to fix this omit $a if it is unset:- I don't know if there's a better way.WARNING: numeric subindexes are lost when merging arrays. Check this example: $a=array('abc'=>'abc','def'=>'def','123'=>'123','xyz'=>'xyz'); echo "a=";print_r($a); $b=array('xxx'=>'xxx'); echo "b=";print_r($b); $c=array_merge($a,$b); echo "c=";print_r($c); The result is this: c=Array ( [abc] => abc [def] => def [0] => 123 [xyz] => xyz [xxx] => xxx )Note that if you use + to merge array in order to preserve keys, that in case of duplicates the values from the left array in the addition is used.In both PHP 4 and 5, array_merge preserves references in array values. For example:I needed a function similar to ian at fuzzygroove's array_interlace, but I need to pass more than two arrays. Here's my version, You can pass any number of arrays and it will interlace and key them properly. Example usage: result: Array ( [0] => a [1] => e [2] => h [3] => k [4] => b [5] => f [6] => i [7] => l [8] => c [9] => g [10] => j [11] => m [12] => d [13] => n [14] => o ) Let me know if you improve on it.i did a small benchmark (on PHP 5.3.3) comparing: * using array_merge on numerically indexed arrays * using a basic double loop to merge multiple arrays the performance difference is huge: So that's more than a factor 100!!!!!The function behaves differently with numbers more than PHP_INT_MAX result: array(3) { ["1234567898765432123456789"]=> string(2) "dd" ["123456789876543212345678"]=> string(3) "ddd" [0]=> string(3) "xxx" } array(3) { [0]=> string(2) "dd" [1]=> string(3) "ddd" [2]=> string(3) "xxx" }array_merge will merge numeric keys in array iteration order, not in increasing numeric order. For example: array_merge($a, $b) will be array(10, 20, 30, 50, 40) and not array(10, 20, 30, 40, 50).As has already been noted before, reindexing arrays is most cleanly performed by the array_values() function.The documentation is a touch misleading when it says: "If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way." Even with two arrays, the resulting array is re-indexed: [bishop@predator staging]$ cat array_merge.php [bishop@predator staging]$ php-5.2.5 array_merge.php array(3) { [0]=> string(7) "I say, " [1]=> string(5) "Hello" [2]=> string(5) "World" } [bishop@predator staging]$ php-4.4.7 array_merge.php array(3) { [0]=> string(7) "I say, " [1]=> string(5) "Hello" [2]=> string(5) "World" }Needed an quick array_merge clone that preserves the keys:Suffice to add, array_merge() creates a new array from the supplied array(s) and does not modify the supplied array(s). Example: $array1 = ["a" => "one", "b"=>"two"]; $array2 = [ "c" => "three", "d" => "four"]; $mergedArray = array_merge($array1, $array2); print_r($mergedArray); // => ["a"=> "one", "b"=> "two", "c"=>"three", "d"=>"four"]; print_r($array1); //=> ["a"=>"one", "b"=>"two"];For those who are getting duplicate entries when using this function, there is a very easy solution: wrap array_unique() around array_merge() cheers, k.To combine several results (arrays): The above example will output: Array ( [0] => Array ( [0] => foo1 ) [1] => Array ( [0] => foo2 ) [2] => Array ( [0] => bar1 ) [3] => Array ( [0] => bar2 ) ) However, example below helps to preserve numeric keys: The above example will output: Array ( [123] => Array ( [0] => foo1 ) [456] => Array ( [0] => foo2 ) [321] => Array ( [0] => bar1 ) [654] => Array ( [0] => bar2 ) )I found the "simple" method of adding arrays behaves differently as described in the documentation in PHP v5.2.0-10. $array1 + $array2 will only combine entries for keys that don't already exist. Take the following example: $ar1 = array('a', 'b'); $ar2 = array('c', 'd'); $ar3 = ($ar1 + $ar2); print_r($ar3); Result: Array ( [0] => a [1] => b ) Where as: $ar1 = array('a', 'b'); $ar2 = array('c', 'd'); $ar3 = array_merge($ar1, $ar2); print_r($ar3); Result: Array ( [0] => a [1] => b [2] => c [3] => d ) Hope this helps someone.Usage of operand '+' for merging arrays: output: Array ( [a] => a1 [b] => a2 [0] => a3 [1] => a4 [2] => a5 [3] => b5 ) numeric keys of elements of array B what not presented in array A was added. output: [a] => a1 [b] => a2 [0] => a3 [1] => a4 [2] => a5 [100] => b1 [101] => b2 [102] => b4 autoindex for array B started from 100, these keys not present in array A, so this elements was added to array AOld behavior of array_merge can be restored by simple variable type casting like this array_merge((array)$foo,(array)$bar); works good in php 5.1.0 Beta 1, not tested in other versions seems that empty or not set variables are casted to empty arraysSometimes we need to traverse an array and group / merge the indexes so that it is easier to extract them so that they are related in the iteration. //OUTPUT Array ( [0] => Array ( [id] => 1 [name] => Hayley [children] => Array ( [0] => Array ( [id] => 2 [name] => Jack [dad] => 1 ) ) ) [1] => Array ( [id] => 4 [name] => Peter [children] => Array ( [0] => Array ( [id] => 3 [name] => Linus [dad] => 4 ) [1] => Array ( [id] => 5 [name] => Tom [dad] => 4 ) ) ) )Similar to Jo I had a problem merging arrays (thanks for that Jo you kicked me out of my debugging slumber) - array_merge does NOT act like array_push, as I had anticipated hope this helps someone$a = array(1,2,3); // an array $b = 5; // anything but not an array $c = array_merge($a, $b); // shows a PHP warning: Argument #2 is not an array var_dump($c); // output as NULL // now merge in reverse order $d = array_merge($b, $a); // shows a PHP warning: Argument #1 is not an array var_dump($d); // output as NULL NOTE: For any operation that relies on the previous array merge operation it is highly necessary to check the arguments as well as the result of the merge are arrays before continuing as the warning would not stop the operation and this might result in data loss and what not... and this should also be stated in the .documentation. somewhat started to demonstrate this but used type casting which made this irrelevant to this matter.Note that if you want to append one array to another, using a foreach in conjuction with array_push is A LOT faster: This in my case resolves to: Test 1: 2.7962880134583s Test 2: 0.0039298534393311sA good function to merge by keys /** * @param $array1....$arrayn */ public function array_merge_keys(){ $args = func_get_args(); $result = array(); foreach($args as $array) { foreach($array as $key=>$value) { $result[$key] = $value; } } return $result; }foreach loop is faster than array_merge to append values to an existing array, so choose the loop instead if you want to add an array to the end of another.public function mergeArrays($arrays, $field) { //take array in arrays for retrive structure after merging $clean_array = current($arrays); foreach ($clean_array as $i => $value) { $clean_array[$i]=''; } $merged_array = []; $name = ''; foreach ($arrays as $array){ $array = array_filter($array); //clean array from empty values if ($name == $array[$field]) { $merged_array[$name] = array_merge($merged_array[$name], $array); $name = $array[$field]; } else { $name = $array[$field]; $merged_array[$name] = $array; } } //have to be cleaned from array 'field' signs to return original structure of arrays foreach ($merged_array as $array){ $ready_array[] = array_merge($clean_array, $array); } return $ready_array; }When mixing string keys and numeric keys, numeric keys are still renumbered after merge. array(4) { ["foo"]=> string(5) "rfoo2" [0]=> string(3) "r21" ["bar"]=> string(5) "rbar2" [1]=> string(3) "r22" } adding arrays doesn't: array(3) { ["foo"]=> string(5) "rfoo2" [2]=> string(3) "r22" ["bar"]=> string(5) "rbar2" }array_merge is the equivalent of concat in other languages. I tried to submit a bug that array_concat should be created as an alias to this but it was rejected on the basis they didn't want to polute the namespace and that the documentation should be updated instead. So here's what I put in the bug #73576: There is no documented array concatenation function. This is a very common function, e.g. Javascript and Ruby have the `concat` function, Python has `+` and Haskell has `++`. The `array_merge` function is what has be used if you want to concatenate arrays. However it is not mentioned in the documentation (not even in the comments) of that method that that is what should be used. I propose that `array_concat` be created as an alias of `array_merge`. The concatenation of an associative array is also consistent with trying to merge the hash maps. For example there is a Stack Overflow question on 'concatenating two dictionaries' that is marked as a duplicate of the function 'How to merge two Python dictionaries'. That is, it is consistent that hash map concatenation is the same as hash map merging. So I believe that `array_concat` is a perfect alias for `array_merge` in terms of numeric arrays and a valid (albeit unnecessary) alias for associative arrays. This will help almost all developers coming to PHP from other dynamic languages.Static functions of Classes with Namespace are callables too. namespace Vendor\Extension\Service; class SvgFormationService implements \TYPO3\CMS\Core\SingletonInterface { public static function doubleQuote($value) { return '"'.$value.'"'; } public static function otherFunc ($value) { $tagAttributes = array_map('\Vendor\Extension\Service\SvgFormationService::doubleQuote',$tagAttributes); } }We noticed array_merge is relatively slower than manually extending an array: given: $arr_one[ 'x' => 1, 'y' => 2 ]; $arr_two[ 'a' => 10, 'b' => 20 ]; the statement: $arr_three = array_merge( $arr_one, $arr_two ); is routinely 200usec slower than: $arr_three = $arr_one; foreach( $arr_two as $k => $v ) { $arr_three[ $k ] = $v; } 200usec didn't matter...until we started combining huge arrays. PHP 5.6.xFor asteddy at tin dot it and others who are trying to merge arrays and keep the keys, don't forget the simple + operator. Using the array_merge_keys() function (with a small mod to deal with multiple arguments), provides no difference in output as compared to +. results in ... array ( -1 => 'minus 1', 0 => 'nought',) array ( -1 => 'minus 1', 0 => 'nought',) array ( -1 => 'minus 1', 0 => 'nought',) array ( -1 => 'minus 1', 0 => 'nought',)Note that if you put a number as a key in an array, it is eventually converted to an int even if you cast it to a string or put it in quotes. That is: $arr["0"] = "Test"; var_dump( key($arr) ); will output int(0). This is important to note when merging because array_merge will append values with a clashing int-based index instead of replacing them. This kept me tied up for hours.If you need to merge two arrays without having multiple entries, try this:I got tripped up for a few days when I tried to merge a (previously serialized) array into a object. If it doesn't make sense, think about it... To someone fairly new, it could... Anyway, here is what I did: (It's obviously not recursive, but easy to make that way) Simple problem, but concevibly easy to get stuck on.
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)