2017-08-12 67 views
0

如何將數組的循環合併到單個數組(可能是對象)中將每個值添加到其關聯的公用密鑰?PHP array_merge_recursive與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會實現我的結果,如果我有$陣列1,在PHP中sepcified $數組2。但我需要從foreach循環中完成。

謝謝。

回答

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

+0

的感謝!這正是我所追求的。問題是,爲什麼'foreach($ collection as&$ item)$ item = array_unique($ item);'因爲這也適用'array_unique($ collection)'。只是出於興趣,因爲兩者都返回相同的結果 – Elliott

+0

@Elliott我在'$ collection'的每個成員上調用'array_unique()',因爲你希望每個子數組都有唯一的值。否則,如果你合併的數組在'category'子數組中有一個'intro'值,那麼你可能會用'category'=> ['intro','intro']'結束。 – BeetleJuice

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