合并多维数组保留键

时间:2018-07-24 09:42:03

标签: php arrays array-merge

所以我有一个如下数组。我想将所有这些合并到key => value的一个数组中。

输入:

$logTypes = array(
    'user_management'   => array(
        1001 => 'A new user was added',
        1002 => '#user_name# accessed user management',
        1003 => 'Created',
        1004 => 'Edited/Updated'),
    'report_management' => array(
        2001 => '#user_name# Added a new report',
        2002 => '#user_name# viewed "edit history" for the report #report_name#',
    ),
);

必需的输出:

array (
  1001 => 'A new user was added',
  1002 => '#user_name# accessed user management',
  1003 => 'Created',
  1004 => 'Edited/Updated',
  2001 => '#user_name# Added a new report',
  2002 => '#user_name# viewed "edit history" for the report #report_name#',
)

我尝试了array_mergearray_maparray_values的各种排列,但是它们只是不能整体使用,就像其中一些设法合并但重新索引键等等。

我的尝试

logTypes = call_user_func('array_merge', array_values(self::$logTypes));

$logTypes = call_user_func('array_push', self::$logTypes);

$logTypes = call_user_func_array('array_merge', self::$logTypes);

$logTypes = array_values(array_values(self::$logTypes));

$array = array_map('current', self::$logTypes);

$merged = array_merge(...self::$logTypes);

最后,我不得不求助于我一直试图避免的事情,遍历每个数组:l

$plain_array = array();
foreach (self::$logTypes as $types) {
    $plain_array += $types;
}

它起作用了,所以现在我的问题是,使用上述array_ *函数还有其他方法来达到期望的结果吗?

如果我可以添加,那么最短的解决方案可能会获胜!:)

2 个答案:

答案 0 :(得分:1)

You can do it like this:

array_reduce($logTypes, function($carry, $item) {
    return $carry + $item;
}, []);

output:

array (
  1001 => 'A new user was added',
  1002 => '#user_name# accessed user management',
  1003 => 'Created',
  1004 => 'Edited/Updated',
  2001 => '#user_name# Added a new report',
  2002 => '#user_name# viewed "edit history" for the report #report_name#',
)

Source: http://php.net/manual/en/function.array-reduce.php

答案 1 :(得分:0)

尝试一下:

$new_array = $logTypes['user_management'] + $logTypes['report_management'];

PHP doc

  

如果要在不覆盖第一个数组中的元素且不重新索引的情况下将第二个数组中的数组元素追加到第一个数组,请使用+数组联合运算符