2014-10-28 157 views
1

鑑於3個集:合併集合在Laravel嵌套對象

$links = new Collection($array_link_objects); 
$images = new Collection($array_image_objects); 
$combined = new Collection(); 

合併它們,以便符合下列條件:

$combined[$i]->link = $links[$i]; 
$combined[$i]->image = $images[$i]; 

編輯:這是不是你經常會有2您需要在鍵上合併並將它們嵌套到屬性中的數組。但如果你這樣做,這是有效的。

+0

你合併了嗎?在第二個組合中還缺少'$'。 – Kypros 2014-10-28 01:21:36

+0

不,我想合併它們,使用集合函數而不是嵌套的foreach語句。 – 2014-10-28 01:22:44

回答

0

這是一個可以完成的方法。

$merged = combine(['link' => $links, 'image' => $image]); 

public function combine($collections) { 
    $merged = new Collection(); 
    $max = count($collections[key($collections)]); 
    for($i = 0; $i < $max; $i++) 
    { 
    $item = new \stdClass(); 
    foreach($collections as $key => $collection) { 
     $item->{$key} = $collection[$i]; 
    } 
    $merged->add($item); 
    } 
    return $merged; 
}