简体   繁体   English

PHP array_merge_recursive与foreach循环

[英]PHP array_merge_recursive with foreach loop

How do you merge a loop of arrays into a single array(maybe object) adding each value to its associated common key? 如何将数组循环合并到单个数组(可能是对象)中,将每个值添加到与其关联的公共键中?

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 )

into

Collection

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

Mycode so far: 到目前为止的Mycode:

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

It seem like array_merge_recursive would achieve my result if I had $array1,$array2 sepcified within the PHP. 如果在PHP中将$ array1,$ array2分隔开,array_merge_recursive似乎可以达到我的结果。 But I need to do from a foreach loop. 但是我需要从一个foreach循环开始。

Thanks. 谢谢。

Given the initial array named $categories , Consider: 给定名为$categories的初始数组,请考虑:

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

Output: 输出:

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

Live demo 现场演示

I suppose this tricky solution: 我想这个棘手的解决方案:

$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)
    );
}

Of course this works since php5.5, as in this version we have array_column . 当然,此功能自php5.5起生效,因为在此版本中,我们具有array_column

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM