-1

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

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

[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

$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?

for ($i = 0 ; $i < sizeof($amount) ; $i++){
                $unitdiff[] = $getunitdiff[$i] - $unit[$i];
                $amountdiff[] = $getamountdiff[$i] - $amount[$i];
            }
Vickel
  • 7,879
  • 6
  • 35
  • 56
Hamza Qureshi
  • 172
  • 2
  • 20
  • to make this easier on everyone can you show the output you want from those 2 input arrays – lagbox Jan 11 '21 at 14:22
  • Your case is not clear. Which of all the arrays in your code are the two arrays you showed at the beginning of your question? – El_Vanja Jan 11 '21 at 14:25
  • thanx for both i have updated code you can check now – Hamza Qureshi Jan 11 '21 at 14:44
  • Does this answer your question? [How to sum values of the array of the same element id](https://stackoverflow.com/questions/27222512/how-to-sum-values-of-the-array-of-the-same-element-id) – STA Jan 11 '21 at 14:48

1 Answers1

1

You could collect the arrays and use map, here is a sample to get you started:

$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 ]
user3532758
  • 2,221
  • 1
  • 12
  • 17