如何使用foreach迭代两个相同长度的集合

时间:2016-12-16 12:25:17

标签: php laravel collections laravel-5 foreach

如果我们想要连接两个集合的某些属性,假设它们具有相同的长度,例如:

收藏1:

man bash

收藏2:

$collection1 = Collection { ▼
  #items: array:2 [ ▼
    0 => Item { ▼
      +id: 1
      +first_name: 'first_name 1'
      +last_name: 'first_name 1'
      +nbr_hours: 9
    }
    1 => Item { ▼
      +id: 2
      +first_name: 'first_name 2'
      +last_name: 'first_name 2'
      +nbr_hours: 10
    }
  ]
}

我们如何能够同时遍历它们并连接$collection2 = Collection { ▼ #items: array:2 [ ▼ 0 => Item { ▼ +id: 1 +first_name: 'first_name 1' +last_name: 'first_name 1' +nbr_hours: 10 } 1 => Item { ▼ +id: 2 +first_name: 'first_name 2' +last_name: 'first_name 2' +nbr_hours: 12 } ] } 属性,例如输出将如下:

nbr_hours

5 个答案:

答案 0 :(得分:1)

首先,要求

需要使用foreach-loop遍历集合的解决方案

使用相同顺序的相同项目的两个集合的方法

您可以使用遍历的每个元素的索引来获取" partner元素"来自其他集合,以防每个集合的项目计数和排序相同。

foreach($collection1 as $index => $item){
    $hours = $item->nbr_hours . $collection2[$index]->nbr_hours;
}

无论排序和项目计数如何

如果您的集合元素的顺序不同,或者集合项计数不同,则查询看起来会更复杂一些。在这种情况下,您需要查询id为相同的元素。为此,我们可以将集合索引更改为包含模型的id。现在我们可以再次使用一个元素的索引来查找另一个元素中的相应元素。

$collection2 = $collection2->keyBy('id'); //Change indexes to model ids 
$collection1 = $collection1->keyBy('id'); //For both collections
foreach($collection1 as $index => $item){
    $hours = $item->nbr_hours . $collection2->get($index)->nbr_hours;
}

答案 1 :(得分:1)

这是一个数组示例,您可以采取哪些措施来实现这一目标 -

$c1 = [
['id' => 1, 'hrs' => 9],
['id' => 2, 'hrs' => 12],
];

$c2 = [
['id' => 1, 'hrs' => 10],
['id' => 2, 'hrs' => 11],
];

foreach($c1 as &$c) {
    // get the index for the id from the 2nd array
    $c2_index = array_search($c['id'], array_column($c2, 'id'));
    // Increment the value
    $c['hrs'] += $c2[$c2_index]['hrs'];
}

Demo

答案 2 :(得分:1)

如果要使用Collection方法,可以使用此方法:

    $zip = $c1->zip($c2->toArray());
    $m = $zip->map(function($items, $key) {
        $sum = 0;
        foreach ($items as $k => $item) {
            $sum += $item['nbr_hours'];
        }
        $r = $items[$k];
        $r['nbr_hours'] = $sum;
        return $r;
    });

基本上,zip方法将"合并"同一个键中的数组。然后,如果使用map方法,则可以迭代主键。之后,您可以将两个数组作为项目处理。因此,您可以进行所需的任何操作,然后返回一个新数组作为结果。

答案 3 :(得分:1)

您可以使用map方法:

$nested_collection  = $collection1->map(function ($item, $key) use($collection2) {
    $item->nbr_hours = $item->nbr_hours + $collection2->get($key)->nbr_hours;
    return $item;
});

注意 - 如果值不在同一个订单上,那么您可以使用values方法。

  

values方法返回一个新集合,其中键重置为连续整数

答案 4 :(得分:1)

@ AmitGupta答案的一个小修改。如果要求集合2与$item->id匹配。试试下面的答案。 :)

$nested_collection = $collection1->map(function($item) use ($collection2) {
    $item->nbr_hours += $collection2->where('id', $item->id)->first()->nbr_hours;

    return $item;
});

让我知道:)。

相关问题