簡體   English   中英

如何在 php 中比較 2 個數組並比較相同 ID 的差異?

[英]how to compare 2 array and compare difference of same id in php?

這個問題被問了很多次,但每個人都使用相同的數組,但在我的情況下,我有 2 個 arrays 考慮我有 2 個 arrays

array1:3 [
  10 => 900.0
  20 => 450.0
  30 => 600.0
]

array2:3 [
  30 => 200.0
  10 => 500.0
  20 => 600.0
]

output 應該是

[900.0 - 500 = 400   // according to same id 10 = 10
 450.0 - 600 = -150  //                       20 = 20
 600.0 - 200 = 400  //                        30 = 30
]

在這個數組中考慮 10,20,30 是 ids,下一個是我想要 output 的值, if (id1 = id2 ){ id1 => value - id2 => value }我需要該代碼的幫助我已經試過了

$getsellerreport = SellerSellsReport::where('seller_id' , $seller_id);
             $getunitdiff = $getsellerreport->pluck('unit')->toArray();// [0 => 75 1 => 500 => 100]
             $getamountdiff = $getsellerreport->pluck('amount')->toArray(); // [0 => 11000 => 40 2 => 900]
             $getproductdiff = $getsellerreport->pluck('product_id')->toArray(); // [0 => 39 1 => 242 => 23]
             
             foreach($product_report as $preport){
                $unit[] = $preport['unit'];// [0 => 75 1 => 25 2 => 100]
                $amount[] = $preport['amount'];// [0 => 900 1 => 450 2 => 600]
                $product_id[] = $preport['product_id'];// [0 => 23 1 => 242 => 39]
               
                } // here we get array two values

上面的代碼獲取從 0 鍵值開始的值,在下面的 for() 循環中,我們可以使用 product_id 來比較產品 ID 並獲取單位和數量,但我不知道我該怎么做有人可以幫助我嗎?

for ($i = 0 ; $i < sizeof($amount) ; $i++){
                $unitdiff[] = $getunitdiff[$i] - $unit[$i];
                $amountdiff[] = $getamountdiff[$i] - $amount[$i];
            }

您可以收集 arrays 並使用 map,這里有一個示例可以幫助您入門:

$a = [
  10 => 900.0,
  20 => 450.0,
  30 => 600.0,
];

$b =  [
  30 => 200.0,
  10 => 500.0,
  20 => 600.0,
];

$x = collect($a)->map(function($aItem, $index) use ($b) {
  return $aItem - $b[$index];
});
dd($x); // yields [ 10 => 400.0, 20 => -150.0, 30 => 400.0 ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM