You are here

function physical_weight_convert in Physical Fields 7

Converts a weight field value array to the specified unit.

Parameters

$weight: A weight field value array including the 'weight' and 'unit'.

$unit: The weight unit type to convert to.

Return value

A weight field value array including the converted 'weight' amount in the target 'unit' type.

File

./physical.module, line 905
Defines fields (e.g. weight and dimensions) to support describing the physical attributes of entities.

Code

function physical_weight_convert($weight, $unit) {

  // If the $weight field value is empty for some reason, return a 0 weight in
  // the target unit type.
  if (empty($weight) || empty($weight['weight'])) {
    return array(
      'weight' => 0,
      'unit' => $unit,
    );
  }

  // If the target unit type is the same as the weight field value that was
  // passed in, simply return it as is.
  if ($weight['unit'] == $unit) {
    return $weight;
  }

  // Convert the weight amount based on the target and source unit type.
  switch ($unit) {
    case 'lb':
      if ($weight['unit'] == 'oz') {
        $multiplier = 0.0625;
      }
      elseif ($weight['unit'] == 'kg') {
        $multiplier = 2.20462262;
      }
      elseif ($weight['unit'] == 'g') {
        $multiplier = 0.00220462262;
      }
      break;
    case 'oz':
      if ($weight['unit'] == 'lb') {
        $multiplier = 16;
      }
      elseif ($weight['unit'] == 'kg') {
        $multiplier = 35.2739619;
      }
      elseif ($weight['unit'] == 'g') {
        $multiplier = 0.0352739619;
      }
      break;
    case 'kg':
      if ($weight['unit'] == 'lb') {
        $multiplier = 0.45359237;
      }
      elseif ($weight['unit'] == 'oz') {
        $multiplier = 0.0283495231;
      }
      elseif ($weight['unit'] == 'g') {
        $multiplier = 0.001;
      }
      break;
    case 'g':
      if ($weight['unit'] == 'lb') {
        $multiplier = 453.59237;
      }
      elseif ($weight['unit'] == 'oz') {
        $multiplier = 28.3495231;
      }
      elseif ($weight['unit'] == 'kg') {
        $multiplier = 1000;
      }
      break;
  }

  // Update the weight amount using the multiplier.
  $weight['weight'] *= $multiplier;

  // Update the unit type to the target type.
  $weight['unit'] = $unit;
  return $weight;
}