Я кодирую инвентарь продуктов. Сейчас я нахожусь в процессе вычисления или преобразования предметов в большую единицу.
Например:
Продукт A: 1 коробка = 12 бутылок
Пользователь может ввести данные, такие как 3 коробки и 13 бутылок при добавлении транзакции. И новое значение для продукта А будет 3 boxes and 13 bottles in storage
, Данные будут сохранены в базу данных tbl_transaction
,
Как я могу автоматически превратить / преобразовать элементы в целом, как 4 boxes and 1 bottle in storage
добавить в мой tbl_storage
?
Я попробовал эту формулу, но я боюсь, что она не точна, когда количество бутылок находится в десятичной запятой.
$bottles = 13;
$box = 12;
$remaining_in_bottle = number_format($bottles / $box);// this will only convert the bottle into box (also tried float but not sure what I am doing)
$total_box = 3 + ???;
echo $total_box." boxes and ".$remaining_in_bottle ." bottles in storage
Я предполагаю, что пользователь вводит только цифры в качестве значений для boxes
а также bottles
, но если нет, вам просто нужно извлечь эти значения из строки перед выполнением следующих вычислений:
Код: (демонстрация)
$bottles_per_box=12;
$user_input_bottles=13;
$user_input_boxes=3;
if($user_input_bottles>$bottles_per_box){
// add truncated integer to box count. DO NOT USE ROUND(), USE FLOOR()
$user_input_boxes+=floor($user_input_bottles/$bottles_per_box);
// store remainder after division
$user_input_bottles=$user_input_bottles%$bottles_per_box;
// ^-- modulo operator
}
echo "New Bottles Total: $user_input_bottles\n";
echo "New Boxes Total: $user_input_boxes\n";
Выход:
New Bottles Total: 1
New Boxes Total: 4
Я предполагаю, что вы хотите ввести разные для tbl_transaction
а также tbl_storage
,
КОД
//Max bottle per box
$box_max_bottles = 12;
//User Input
$input_box = 3;
$input_bottle = 13;
//Transaction
$transaction = (($input_box > 1) ? $input_box . ' boxes' : $input_box . ' box')
. ' and ' . (($input_bottle > 1) ? $input_bottle. ' bottles' : $input_bottle. ' bottle'). ' in storage';
//Data will save into database tbl_transaction
echo $transaction;
//Get the remainder which is the remaining bottle
$total_bottle = $input_bottle % 12;
//Get the total boxes and divide the bottle into 12
$total_box = floor($input_box + ($input_bottle / 12));
echo "<br />";
//Storage
$storage = (($total_box > 1) ? $total_box . ' boxes' : $total_box . ' box')
. ' and ' . (($total_bottle > 1) ? $total_bottle . ' bottles' : $total_bottle . ' bottle'). ' in storage';
//Data will save into database tbl_storage
echo $storage;
ВЫХОД
Сделка
3 boxes and 13 bottles in storage
Место хранения
4 boxes and 1 bottle in storage