我有兩個多維陣列,如下所示:
陣列 01 用于商品的新價格:
Array
(
[42] => Array
(
[0] => 110
[1] => 0.00
)
[41] => Array
(
[0] => 80
[1] => 70.00
)
[43] => Array
(
[0] => 70
[1] => 60
)
[40] => Array
(
[0] => 90
[1] => 80
)
)
1
陣列 02 用于物品的舊價格:
Array
(
[42] => Array
(
[sales_price] => 100.00
[our_price] => 0.00
)
[41] => Array
(
[sales_price] => 80.00
[our_price] => 0.00
)
)
1
兩個陣列的陣列鍵都是專案 ID(42、41、43、40)。現在我需要比較 $new 和 $old 陣列來創建更新和插入查詢。
如果新陣列中的值與舊陣列中的值不同,則應更新表。如果新陣列中的元素比舊陣列中的元素多,則應為插入查詢識別它們。
所以基本上我想將新陣列分為兩部分,比較舊陣列并考慮上述條款。
期望兩個陣列應如下所示:
Array
(
[42] => Array
(
[0] => 110
[1] => 0.00
)
[41] => Array
(
[0] => 80
[1] => 70.00
)
)
1
Array
(
[43] => Array
(
[0] => 70
[1] => 60
)
[40] => Array
(
[0] => 90
[1] => 80
)
)
1
這是我到目前為止的代碼:
foreach ($priceNew as $newIds => $newPrices) {
foreach($priceOld as $oldIds => $oldPrices) {
}
}
有人可以幫我劃分我的新陣列嗎?
uj5u.com熱心網友回復:
此資料已以這樣一種方式更改,即新的鍵為 41 的元素與舊的元素匹配。
$priceNew = [
42 => [ 110, 0.00 ],
41 => [ 80, 70.00 ],
43 => [ 70, 60 ],
40 => [ 90, 80 ],
];
$priceOld = [
42 => [
'sales_price' => 100.00,
'our_price' => 0.00
],
41 => [
'sales_price' => 80.00,
'our_price' => 70.00
],
];
你只需要比較密鑰。這可以通過內部 PHP 函式array_intersect_key和array_diff_key來完成。更新陣列仍然被過濾以滿足特殊條件。
$updateArr = array_intersect_key($priceNew, $priceOld);
$filter = function($v,$k) use($priceOld){
return array_values($priceOld[$k]) != $v;
};
$updateArr = array_filter($updateArr, $filter, ARRAY_FILTER_USE_BOTH );
$otherArr = array_diff_key($priceNew,$updateArr); //added or remained
uj5u.com熱心網友回復:
我想我理解你所說的足以為 PHP > 8 制作這個......
$priceNew = [
42 => [ 110, 0.00 ],
41 => [ 80, 70.00 ],
43 => [ 70, 60 ],
40 => [ 90, 80 ],
];
$priceOld = [
42 => [
'sales_price' => 100.00,
'our_price' => 0.00
],
41 => [
'sales_price' => 80.00,
'our_price' => 0.00
],
];
$updateItems = [];
$insertItems = [];
foreach( $priceNew as $id => $values ) {
$old = $priceOld[ $id ] ?? null;
if ( !$old ) {
$insertItems[ $id ] = $values;
} else {
// Not sure if this is the correct conditions, might need to change.
if ( $values[ 0 ] !== $old[ 'sales_price' ] || $values[ 1 ] !== $old[ 'our_price' ] ) {
$updateItems[ $id ] = $values;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/464632.html
上一篇:在不同的方法中拆分長方法
