2017-11-22 12 views
2

제품 인벤토리를 코딩하고 있습니다. 이제는 아이템을 계산하거나 더 큰 단위로 변환하는 중입니다. 예를 들어인벤토리 제품 계산 및 변환

: 제품 A : 1 상자 = 12 병

사용자 입력 할 수 3 박스 13 병 트랜잭션을 추가하는 등 데이터. 제품 A의 새 값은 3 boxes and 13 bottles in storage입니다. 데이터는 데이터베이스 tbl_transaction에 저장됩니다.

tbl_storage에 추가하려면 4 boxes and 1 bottle in 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 

답변

2

나는 사용자가 boxesbottles 값으로 단지 숫자를 inputing되는 가정 만하고 당신은 단순히 다음과 같은 계산을 수행하기 전에 문자열에서이 값을 추출 할 필요가없는 경우 :

코드 : (Demo를)

$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 
+0

입력 해 주셔서 감사합니다. 아주 간단합니다. 건배! 나는 나머지를 얻을 때'%'를 사용하는 방법을 알기를 바랍니다. –

+0

참조 : http://php.net/manual/en/language.operators.arithmetic.php – mickmackusa

+0

나머지 결과가 10 진수 일 가능성이 있습니까? –

1

난 당신이 tbl_transactiontbl_storage에 대해 서로 다른 입력한다고 가정합니다.

CODE

//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; 

OUTPUT

거래

3 boxes and 13 bottles in storage 

저장

,
4 boxes and 1 bottle in storage 
+0

이 답변 주셔서 감사합니다! 정말 감사. 당신과 mickmackusa는 올바른 해결책을 가지고 있지만 그것은 내 상황에 더 적용 가능하기 때문에 mickmackusa의 답과 해결책을 받아들입니다. 고맙습니다. –

+1

솔직히 말해서, 이것은 올바른 방법이 아닙니다. 적어도'round() '때문에 코드를 테스트하지는 않았지만'round()'가 올바르지 않습니다. 내 대답을 읽고 당신을 업데이트하십시오. – mickmackusa

+2

@mickmackusa 네가 맞아. 나는 당신의 대답을 읽고'round()'가 .5+ .and가 미래에 올바른 결과를 내지 않을 수도 있기 때문에'floor()'가 대신 사용되어야한다. 그걸 알아 채지 못 했어. 그것을 지적 주셔서 감사합니다. – Bluetree