【问题标题】:How can i sum an array like this in laravel我如何在 laravel 中对这样的数组求和
【发布时间】:2020-06-18 22:37:52
【问题描述】:

我从表中的两行返回了这个,我希望能够在 laravel Blade 中显示总和。

["212,703.00","212,703.00"]

我试过了,但没有用。列名是amount

 $investamount = DB::table('investment')->get();
 return $investamount->sum('amount');

【问题讨论】:

标签: laravel laravel-5


【解决方案1】:

看来您正在使用 varchar 作为您的 amount 带有逗号的字段,那么您可以这样做

DB::table('investment')->select("SUM(REPLACE(amount, ',', '')") as total)->get()

【讨论】:

  • SQLSTATE[42S22]:未找到列:1054 '字段列表中的未知列'SUM(amount)'
  • @PPK你可以直接使用sum方法
  • 使用聚合方法作为sum时不需要使用get()。使用
  • 是的,我之前尝试过,但它给了我 424 作为 212,703.00","212,703.00" 的总和...... 703、703 会发生什么??
  • 703 是否存储在不同的列中?
【解决方案2】:

使用

$investamount = DB::table('investment')->sum('amount');

$investamount = DB::table('investment')->pluck('amount')->toArray();
$sum = array_sum($investamount);

已编辑

$investamount = DB::table('investment')->select(DB::raw("SUM(amount) as sum"))->get();
return $investamount->sum;

【讨论】:

  • 我需要 212,703.00 + 212,703.00 的答案,但我得到的是 424 作为答案。
  • 我认为您将金额保存为 sting ,因此答案已更新,请尝试
【解决方案3】:

您需要使用 array_reduce 来处理您拥有的特殊格式

$investamount = DB::table('investment')->pluck('amount')->toArray();
$investamount = array_reduce($investamount, function($carry, $item) {
    return $carry + str_replace(',','',$item);
});

【讨论】:

  • 未定义变量:进位
  • compact():未定义变量:投资金额
  • @PPK 再试一次,打错了。资本为 A 的投资金额
  • @PPK 它在变量 $sum 中,我已经对其进行了编辑。在这里,命名随心所欲..
  • 工作这就是答案
【解决方案4】:

这是你需要的

return DB::table('investment')->get()->sum(function ($investment) {
    return (float) str_replace(',', '', $investment->amount);
});

【讨论】:

  • 不能使用 stdClass 类型的对象作为数组
  • 不起作用,“,”是千位分隔符而不是小数位分隔符。已经有一个“。”在号码中
【解决方案5】:

你可以使用 laravel Collections 来实现。然后映射项目以替换逗号。

示例:

return collect(DB::table('investment')->select('amount')->get())->map(function ($item) {
  return str_replace(',', '', $item->amount);
})->sum(); //This will return 425406‬.00

如果您想在刀片模板中使用逗号显示总和,您可以使用number_format()

示例:

{{ number_format(sum, 2) }} //425,406‬.00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-15
    • 2020-08-06
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 2013-06-28
    • 1970-01-01
    相关资源
    最近更新 更多