Weight.class.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace Lib;
  3. class Weight {
  4. private $weights = array();
  5. public function __construct() {
  6. $weight_class_query = M()->query("SELECT * FROM " . C('DB_PREFIX') . "weight_class");
  7. foreach ($weight_class_query as $result) {
  8. $this->weights[$result['weight_class_id']] = array(
  9. 'weight_class_id' => $result['weight_class_id'],
  10. 'title' => $result['title'],
  11. 'unit' => $result['unit'],
  12. 'value' => $result['value']
  13. );
  14. }
  15. }
  16. //单位换算,并返回计算结果
  17. public function convert($value, $from, $to) {
  18. if ($from == $to) {
  19. return $value;
  20. }
  21. if (isset($this->weights[$from])) {
  22. $from = $this->weights[$from]['value'];
  23. } else {
  24. $from = 0;
  25. }
  26. if (isset($this->weights[$to])) {
  27. $to = $this->weights[$to]['value'];
  28. } else {
  29. $to = 0;
  30. }
  31. return $value * ($to / $from);
  32. }
  33. //格式化
  34. public function format($value, $weight_class_id, $decimal_point = '.', $thousand_point = ',') {
  35. if (isset($this->weights[$weight_class_id])) {
  36. /**
  37. * php函数number_format(),通过千位分组来格式化数字,
  38. * 参数1,要格式化的数字
  39. * 参数2,规定多少位小数
  40. * 参数3,小数点字符串
  41. * 参数4 , 千位分格符字符串
  42. */
  43. return array(
  44. 'num'=>number_format($value, 2, $decimal_point, $thousand_point),
  45. 'format'=>number_format($value, 2, $decimal_point, $thousand_point) . $this->weights[$weight_class_id]['unit']
  46. );
  47. } else {
  48. return array(
  49. 'num'=>number_format($value, 2, $decimal_point, $thousand_point),
  50. );
  51. }
  52. }
  53. public function getUnit($weight_class_id) {
  54. if (isset($this->weights[$weight_class_id])) {
  55. return $this->weights[$weight_class_id]['unit'];
  56. } else {
  57. return '';
  58. }
  59. }
  60. }
  61. ?>