检查下面的数组print_r()视图。我想要总共只有"金额"值。并且输出不应该在数组中。它应该是一个简单的整数值。所以结果应该是4 + 3 + 9 = 16
Array
(
[0] => Array
(
[id] => 15
[portfolio_id] => 1
[stock_id] => 1
[amount] => 4
[date] => 04/02/2017
[created_at] => 2017-04-02 09:04:30
[updated_at] => 2017-04-02 09:04:30
)
[1] => Array
(
[id] => 14
[portfolio_id] => 1
[stock_id] => 3
[amount] => 3
[date] => 04/02/2017
[created_at] => 2017-04-02 09:03:40
[updated_at] => 2017-04-02 09:03:40
)
[2] => Array
(
[id] => 13
[portfolio_id] => 1
[stock_id] => 4
[amount] => 9
[date] => 04/02/2017
[created_at] => 2017-04-02 09:03:36
[updated_at] => 2017-04-02 09:03:36
)
)
答案 0 :(得分:3)
尝试array_sum(array_column($input, 'amount'));
array_column
将返回amount
键&的值array_sum
计算返回数组中值的总和
答案 1 :(得分:0)
试试这个:
function sum($carry, $item)// summing on amount column of the inner array $item
{
$carry += $item["amount"];
return $carry;
}
echo "Amount sum : ".array_reduce($a, "sum");// output : 59
示例:
<?php
/**
* Created by PhpStorm.
* User: lenovo
* Date: 4/2/2017
* Time: 11:17 AM
*/
$array = array
(
array("name"=>"Volvo","amount"=>22,"id"=>18),
array("name"=>"BMW","amount"=>15,"id"=>13),
array("name"=>"Saab","amount"=>5,"id"=>2),
array("name"=>"Land Rover","amount"=>17,"id"=>15)
);
function sum($carry, $item)
{
$carry += $item["amount"];
return $carry;
}
echo "Amount sum : " .array_reduce($array, "sum");// output : 59
祝你好运。