我在laravel中有一个名为$destinations
的数组,其值为:
Collection {#391 ▼
#items: array:2 [▼
"Chicago, Illinois" => Collection {#398 ▼
#items: array:10 [▶]
}
"New York City, New York" => Collection {#403 ▼
#items: array:10 [▶]
}
]
}
此数组按城市名称分组,就像芝加哥和纽约一样,现在我想在城市名称后添加一个数组项目,它应该是这样的:
Collection {#391 ▼
#items: array:2 [▼
"Chicago, Illinois" => Collection {#398 ▼
#items: array:10 [▶]
"days" => "2"
}
"New York City, New York" => Collection {#403 ▼
#items: array:10 [▶]
"days" => "7"
}
]
}
我在循环数组时尝试使用array_merge
,我在循环中使用foreach($destinations as $key => $destination)
,基本上$key
会返回增量编号,如 0 < / strong>, 1 , 2 等,但在这种情况下,它会返回城市名称。谁知道怎么做?或者如何在laravel中分组之后使$key
仍为增量数?
答案 0 :(得分:1)
我看到你的declare @DBOrderItem table
(
OrderItemGuid UniqueIdentifier default newid(),
Name VarChar(100)
);
declare @PayloadOrderItem table
(
OrderItemGuid UniqueIdentifier default newid(),
Name VarChar(100)
);
insert into @DBOrderItem (Name) values ('Phone');
insert into @DBOrderItem (Name) values ('Laptop');
insert into @PayloadOrderItem
select top 1 * from @DBOrderItem;
insert into @PayloadOrderItem (Name) values ('Tablet');
select doi.OrderItemGuid,
doi.Name,
case when poi.OrderItemGuid is null then 'Delete' else 'Update' end ActionType
from @DBOrderItem doi
left join @PayloadOrderItem poi on doi.OrderItemGuid = poi.OrderItemGuid
union
select poi.OrderItemGuid,
poi.Name,
'Add' ActionType
from @PayloadOrderItem poi
left join @DBOrderItem doi on doi.OrderItemGuid = poi.OrderItemGuid
where doi.OrderItemGuid is null;
变量是一个集合。因此,您可以使用$destinations
方法迭代它。
例如:
each
要获得增量编号,您可以执行以下操作:
$destinations = $destinations->each(function ($item, $key) {
// You can modify $item here
// $item['days'] = <no_of_days>;
});