Fateh Alrabeai
Fateh Alrabeai

Reputation: 730

How to mutiply array of quantities by each item price?

I'm trying to multiply each item price with quantity inside array. this is the request I get from the mobile through api : I used dd($request->all());

array:2 [
  9 => "4"
  8 => "6"
]

//where(9,8) are the item ids and 4,6 are the quantities
  $req = $request->all();
 $items= [];
        foreach ($req as $key => $value){
            $items[] = [
                "item_id" =>$key ,
                "quantity" =>$value ,
            ];
        }

   $ids= [];
        foreach ($req as $key => $value){
            $ids[] = $key;
        }

        $qunts = [];
        foreach ($req as $key => $value){
            $qunts[] = (int)$value;
        }

        $items = Item::whereIn('id',$ids)->get();

//here I'm trying to mutiply each item price with it's quantity comming from the request

        $priceTotal = 0;
        foreach($items as $item) {
            $subtotal = $item->price *  $qunts;
            $priceTotal += $subtotal;
        }

Upvotes: 0

Views: 50

Answers (2)

Qonvex620
Qonvex620

Reputation: 3972

You could do it in this way.

foreach($items as $key => $item) {
     $subtotal = $item->price *  $qunts[$key];
     $priceTotal += $subtotal;
}

Upvotes: 1

Rakesh Jakhar
Rakesh Jakhar

Reputation: 6388

You are not using the id of the item to get the quantity, do it in this way

 foreach($itemModels as $model) {
        $priceTotal += $model->price *  $req[$model->id]; 
    }

Upvotes: 1

Related Questions