简体   繁体   English

如何在 php 中比较 2 个数组并比较相同 ID 的差异?

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

this questin is asked many times but every one using same array but in my case i have 2 arrays consider i have 2 arrays这个问题被问了很多次,但每个人都使用相同的数组,但在我的情况下,我有 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 should be output 应该是

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

in this array consider 10,20,30 are ids and next is value i want output where compare ever id and get difference example if (id1 = id2 ){ id1 => value - id2 => value } i need help in that code which i already tried在这个数组中考虑 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

above code get values with starting 0 key value and on below for() loop we can use product_id to compare both product id and get unit and amount but i dont know how i can do that can someone help me?上面的代码获取从 0 键值开始的值,在下面的 for() 循环中,我们可以使用 product_id 来比较产品 ID 并获取单位和数量,但我不知道我该怎么做有人可以帮助我吗?

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

You could collect the arrays and use map, here is a sample to get you started:您可以收集 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