在 Elias 的 array_merge_recursive 答案的基础上,以下介绍了将单个项目合并为数组的小修复:
/* This version uses the function array_merge_recursive to collect
* all of the values for the nested arrays by key
*
* @see http://willem.stuursma.name/2011/09/08/parallel-array_map-with-hiphop/
* @see http://willem.stuursma.name/2010/11/22/a-detailed-look-into-array_map-and-foreach/
* for why for loops are better than array_map in general
*/
$result = array_map(function($item) {
/* The array_merge_recursive function doesn't add
* values to an array if there was only one found
* if the item isn't an array, make it an array
*/
return is_array($item) ? $item : array($item);
/* Calls the array_merge_recursive function applying all of
* the nested arrays as parameters.
*
* @see http://php.net/array_merge_recursive
* @see http://www.php.net/call_user_func_array
*/
}, call_user_func_array('array_merge_recursive', $arr));
生产:
Array
(
[color] => Array
(
[0] => green
[1] => brown
)
[width] => Array
(
[0] => 34
)
)
代替:
Array
(
[color] => Array
(
[0] => green
[1] => brown
)
[width] => 34
)
另外,ComFreek 的 array_column 解决方案的动态方法。
这为您提供了键的数组:
/* Gets the keys of the nested arrays as a single array of keys by first
* mapping the nested arrays to an array of keys they contain and then
* by merging these arrays and killing duplicates
*
* @see http://php.net/function.array-unique
* @see http://www.php.net/call_user_func_array
* @see http://www.php.net/array_merge
* @see http://www.php.net/array_map
*/
$keys = array_unique(call_user_func_array('array_merge', array_map(function($item) {
/* Replaces the nested array of keys and values with an array
* of keys only in the mapped array
*
* @see http://www.php.net/array_keys
*/
return array_keys($item);
}, $arr)));
作为:
Array
(
[0] => color
[1] => width
)
可以和这个sn-p一起使用:
/* Combines the array of keys with the values from the nested
* arrays.
*
* @see http://php.net/array_combine
* @see http://www.php.net/manual/en/function.array-map.php
*/
$result = array_combine($keys, array_map(function($key) use($arr) {
/* Collects the values from the nested arrays
*
* @see http://php.net/array_column
*/
return array_column($arr, $key);
}, $keys));
创建所需的输出:
Array
(
[color] => Array
(
[0] => green
[1] => brown
)
[width] => Array
(
[0] => 34
)
)
注意: 函数式调用在大多数语言中比命令式风格更有益,尽管它确实需要在思想上有所转变。功能模式开辟了低级优化的可能性,否则这些优化是不可能的。例如,数组映射可以并行执行,而 for 循环不能,for 循环总是有一个限制,它必须按顺序执行。