在array_sum中PHP计算错误

时间:2018-01-09 21:13:09

标签: php arrays array-sum

我正在尝试加上所有数组值,如:

$arr = array('55','55','99'); // I want to do 55 + 55 + 99 = X

我的功能:

function get_value_of_vouchers($id){
  global $db;
  $prices = array();
  $query = $db->query("SELECT * FROM vouchers WHERE uid='$id' ORDER BY id");
  if ($query->num_rows > 0) {
    while ($row = $query->fetch_assoc()) {
      $fixed_prices = get_price_by_id($row['price']); 
      // returned e.g : 250 | 500 | 1500
      array_push($prices, $fixed_prices);  

      //var_dump($prices); - Printed - array(1) { [0]=> string(4) "5000" } array(2) { [0]=> string(4) "5000" [1]=> string(3) "250" } array(3) { [0]=> string(4) "5000" [1]=> string(3) "250" [2]=> string(3) "250" }
      return array_sum($prices);
    }
  }
}

总是当我尝试做array_sum时,我得到一个错误的号码。

1 个答案:

答案 0 :(得分:2)

为什么不简单地从sql查询中执行此操作

$query = $db->query("SELECT SUM(price) as total_price FROM vouchers WHERE uid='$id' ORDER BY id");

更好地使用下面的准备好的声明

 $stmt=$mysqli->prepare("SELECT SUM(price) as total_price FROM vouchers WHERE uid=? ORDER BY id");
 $stmt->bind_param("i", $id);
 $stmt->execute();
 $stmt->bind_result($total);
 $stmt->fetch();
 echo $total;