带有foreach循环的PHP array_merge_recursive

时间:2017-08-12 19:06:42

标签: php arrays foreach

如何将一个数组循环合并到一个数组(可能是对象)中,将每个值添加到其关联的公共密钥中?

Categories: 

Array ( [category] => introduction [timeZone] => Europe/Stockholm [language] => Danish )

Array ( [category] => introduction [timeZone] => Europe/Stockholm [language] => Danish )

Array ( [category] => e-learning [timeZone] => Europe/Stockholm [language] => German )

Collection

Array ( 
        [category] => Array (e-learning,introduction) 
        [timeZone] => Europe/Stockholm 
        [language] => Array (Danish,German)
)
到目前为止

Mycode:

foreach ($categories as $category){
   $collection = array_merge_recursive($category);
}

看起来像array_merge_recursive会实现我的结果,如果我在PHP中使用$ array1,$ array2 sepcified。但我需要从foreach循环开始。

感谢。

2 个答案:

答案 0 :(得分:1)

给定名为$categories的初始数组,请考虑:

$collection = array_merge_recursive(...$categories);
foreach($collection as &$item) $item = array_unique($item);

输出:

[
  'category' => ['intro','learning'],
  'timezone' => ['Europe'],
  'language' => ['Danish','German'],
]

Live demo

答案 1 :(得分:0)

我想这个棘手的解决方案:

$collection = [];
// get keys of a first element of categories
$keys = array_keys($categories[0]);
// iterate over these keys
foreach ($keys as $key) {
    // use `array_unique` to eliminate duplicates
    $collection[] = array_unique(
        // `array_column` will give you all values under `$key`
        array_column($categories, $key)
    );
}

当然这是自php5.5起作用的,因为在这个版本中我们有array_column