How to create 2 collections based from an array with 2 count in PHP?

Viewed 39

I know this is a basic question and I'm sorry I can't answer, but how can I create 2 collections based from an array with 2 values in Laravel/PHP? Here's my code:

 $received_items = ReceiveItems::where('voucher_id', '=', $request->voucher_id)->get();
        foreach($received_items as $received_item) {
            $product_ids = $received_item->product_id;
            foreach($product_ids as $product_item_no => $product_id) {
                $products = Product::where('id', '=', $product_id); 
                $voucher_cost = $products->value('cost');
                $qty_addend = $received_item->qty_per_item;

                $list = array(
                    'product_item_no' => $product_item_no + 1,
                    'product_name' => $products->value('name'),
                    'size' => $products->value('size'),
                    'qty_addend' => $qty_addend[$product_item_no],
                    'voucher_cost' => $voucher_cost,
                    'ext_cost' => number_format($voucher_cost * $qty_addend[$product_item_no], 2)
                );

                $list = (object)$list;
                $received_item->list = $list;
                $data = collect([$list]);
            }
        }
        return $data;

Basically, the $product_ids is the array I want to get and count($product_ids) is returning 2, but it's just creating the collection from the 2nd array value. See screenshot below:

screenshot.png

Any help is much appreciated.

1 Answers

In your $list variable it will only store last product_id data, because you have to take $list as multi-dimensional array. You have to take $list variable out of the second loop, so it not overwrite data.

Try below code:

$received_items = ReceiveItems::where('voucher_id', '=', $request->voucher_id)->get();
foreach($received_items as $received_item) {
   $product_ids = $received_item->product_id;
   $list = []; // declare list variable here
   foreach($product_ids as $product_item_no => $product_id) {
       $products = Product::where('id', '=', $product_id);
       $voucher_cost = $products->value('cost');
       $qty_addend = $received_item->qty_per_item;

       $list[] = array( // make it multi-dimentional array
           'product_item_no' => $product_item_no + 1,
           'product_name' => $products->value('name'),
           'size' => $products->value('size'),
           'qty_addend' => $qty_addend[$product_item_no],
           'voucher_cost' => $voucher_cost,
           'ext_cost' => number_format($voucher_cost * $qty_addend[$product_item_no], 2)
       );
   }
   // take this code out of loop
   $list = (object)$list;
   $received_item->list = $list;
   $data = collect([$list]);
}
return $data;
Related