Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an alternative for array_merge?

The problem is, I'm not getting the expected results of my array code.

I've tried doing the array_merge, but all it does was to merge all the arrays.

$medicine_order = $request['medicine_id'];

        array:3 [▼
          0 => "25"
          1 => "32"
          2 => "30"
      ]

      $medicine_quantity = $request['medicine_quantity'];

      array:3 [▼
          0 => "3"
          1 => "10"
          2 => "6"
      ]

      $count = 0;
      foreach ($medicine_order as $id) {
        $item = new Historyitem;
        $item->medicine_id = $id;

        foreach ($medicine_quantity as $id2) {
            $item->historyitem_quantity = $id2;
        }
        $item->save();
        $count++;
    }

I wanted to store these values in my DB.

array:3 [▼
          0 => "25"
          1 => "3"
      ]
 array:3 [▼
          0 => "32"
          1 => "10"
      ] 
array:3 [▼
          0 => "30"
          1 => "6"
      ]

but instead I get these values:

array:3 [▼
          0 => "25"
          1 => "6"
      ]
 array:3 [▼
          0 => "32"
          1 => "6"
      ] 
array:3 [▼
          0 => "30"
          1 => "6"
      ]
like image 732
F.ture Avatar asked Dec 03 '25 14:12

F.ture


1 Answers

Solution is change your foreach loop to this:

$count = 0;
foreach ($medicine_order as $key=>$id) {
    $item = new Historyitem;
    $item->medicine_id = $id;
    $item->historyitem_quantity = $medicine_quantity[$key];
    $item->save();
    $count++;
}

Reason why you are getting wrong result is, your internal foreach loop, it iterates over every element of your $medicine_quantity array and every time it replaces the older value with new value, hence you are getting the value of last index i.e., "6" in final result.

like image 61
Hirdesh Vishwdewa Avatar answered Dec 05 '25 04:12

Hirdesh Vishwdewa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!