如何在php中比较2个数组和相同id的差异?
这个questin被问了很多次,但每个都使用相同的数组,但在我的例子中,我有两个数组 假设我有2个数组如何在php中比较2个数组和相同id的差异?,php,laravel,laravel-5,Php,Laravel,Laravel 5,这个questin被问了很多次,但每个都使用相同的数组,但在我的例子中,我有两个数组 假设我有2个数组 array1:3 [ 10 => 900.0 20 => 450.0 30 => 600.0 ] array2:3 [ 30 => 200.0 10 => 500.0 20 => 600.0 ] 输出应为 [900.0 - 500 = 400 // according to same id 10 = 10 450.0 - 6
array1:3 [
10 => 900.0
20 => 450.0
30 => 600.0
]
array2:3 [
30 => 200.0
10 => 500.0
20 => 600.0
]
输出应为
[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,其次是值<强> I输出,这里比较常量ID,得到不同的例子:代码>(ID1=ID2){ID1=>值-ID2= >值} /代码> < /强>
在我已经尝试过的代码中,我需要帮助
$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来比较product id并获取单位和金额,但我不知道我该怎么做有人能帮我吗
for ($i = 0 ; $i < sizeof($amount) ; $i++){
$unitdiff[] = $getunitdiff[$i] - $unit[$i];
$amountdiff[] = $getamountdiff[$i] - $amount[$i];
}
for($i=0;$i
您可以收集阵列并使用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 ]
为了让每个人都更容易理解,你可以展示你想要从这两个输入阵列中获得的输出。你的情况不清楚。您的代码中的所有数组中,哪一个是您在问题开始时显示的两个数组?thanx对于这两个数组,我已经更新了代码,您现在可以检查这是否回答了您的问题?这不会解决我的问题,因为我的键值从0开始。数组中的键值为0不会出现问题。您的代码帮助了我