arrays - 将 laravel 中具有键值对的两个对象数组与特定键进行比较,并返回不匹配的键值
问题描述
我有两个数组: OrderItem:
[
{
"id": 4,
"cancel": 0,
"deleted_at": null,
"created_at": "2020-08-12T10:14:01.000000Z",
"updated_at": "2020-08-12T10:14:01.000000Z"
},
{
"id": 3,
"cancel": 0,
"created_at": "2020-08-12T10:14:56.000000Z",
"updated_at": "2020-08-12T10:14:56.000000Z",
}
]
订单就绪:
[
{
"id": 2,
"order_item_id": 4,
"date": "1962-04-13",
"wages": 12,
"deleted_at": null,
"created_at": "2020-08-12T10:14:56.000000Z",
"updated_at": "2020-08-12T10:14:56.000000Z",
}
]
所以我需要用OrderItem
表中的 order_item_id 从表中检查 idOrderReady
并从 OrderItam 表中返回记录,以防 id 在 OrderReady 表中不存在。从上面的数据中,返回 OrderItem 表的 id 为 3 的记录,因为它没有出现在 OrderReady 表中。什么是最快和最有效的方法?
解决方案
这里有两个关于如何做到这一点的建议。你会得到一种丑陋的方式和一种更漂亮的方式。
首先,我们迭代所有项目并与准备好的项目匹配。如果未找到匹配项,则将该项目添加到“未准备好的项目”列表中,以供以后处理。
$orderItems = [
['id' => 1], ['id' => 2], ['id' => 3]
];
$orderReadyItems = [
['order_item_id' => 1], ['order_item_id' => 3]
];
// Array for storing items that are not yet ready
$notReadyItems = [];
foreach($orderItems as $item) {
$itemReady = false;
// Iterate all ready items and attempt to find a match with item.
foreach($orderReadyItems as $orderReadyItem) {
if ($item['id'] === $orderReadyItem['id']) {
$itemReady = true;
break; // Stop iterating ready items if a match is found.
}
}
// Add item to $notReadyItems array if no match is found.
if ($itemReady === false) {
$notReadyItems[] = $item;
}
}
为了让它看起来更漂亮一点,我们可以利用一些 Collection 方法。因此,我们不是迭代所有准备好的项目,而是创建一个包含所有准备好的项目 ID 的数组,并在 orderItems 的过滤器中检查它,如下所示:
$readyItemIds = collect($orderReadyItems)->pluck('order_item_id');
$notReadyItems = collect($orderItems)->filter(static function (array $item) use ($readyItemIds) {
return !$readyItemIds->contains($item['id']);
});
倾倒$notReadyItems
应该给你:
array:1 [
0 => array:1 [
"id" => 2
]
]