2014-10-28 247 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; 
}