0

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

$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 时,我得到一个错误的数字。

4

1 回答 1

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;
于 2018-01-09T21:17:08.743 回答