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"
]
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.
You need to process the $medicine_quantity
values in the same order as the $medicine_order
values, which you can do by matching the keys to each array. Try this instead:
foreach ($medicine_order as $key => $id) {
$item = new Historyitem;
$item->medicine_id = $id;
$item->historyitem_quantity = $medicine_quantity[$key];
$item->save();
$count++;
}