我所看到的各种发布了关于这个问题,所以我知道一些答案,这可能存在。 但是我没有看完这些明智的。
我有一个数组,它是像下面这样。
[0] => Array
(
[id] => 95659865986
[invoiceNumber] => 6374324
[invoiceTitle] => Monthly
[invoiceStatus] => Paid
[accountId] => 6235218753
[totalExVat] => 158.95
[dateCreated] => 1 Apr 2012
[vatAmount] => 20.00
)
我所希望做的是做对阵列和vatAmount
这个数组的值。
如下面的似乎并不被太多这样做。
(array_sum($account_invoices['vatAmount'])
Answer 1:
只是一个办法做到这一点:
$sum = 0;
foreach($account_invoices as $num => $values) {
$sum += $values[ 'vatAmount' ];
}
Answer 2:
如果你有PHP 5.5或以上版本,你可以这样做没有循环或使用回调(因为函数调用是相对昂贵的)...只需使用:
$sum = array_sum(array_column($account_invoices, 'vatAmount'));
Answer 3:
我会用array_map到阵列减少必要的东西。 请记住,这只会用PHP 5.3开始工作。
$total_vat = array_sum( array_map(
function($element){
return $element['vatAmount'];
},
$account_invoices));
Answer 4:
你可以使用array_map
先收集vatAmout
值。
$sum = array_sum(array_map(function($var) {
return $var['vatAmout'];
}, $account_invoices));
Answer 5:
一种方法可以做到这一点使用一个PHP 5.3+匿名函数
$account_invoices = array(
0 => array(
'id' => '95659865986',
'invoiceNumber' => '6374324',
'invoiceTitle' => 'Monthly',
'invoiceStatus' => 'Paid',
'accountId' => '6235218753',
'totalExVat' => 158.95,
'dateCreated' => '1 Apr 2012',
'vatAmount' => 20.00
),
1 => array(
'id' => '95659865987',
'invoiceNumber' => '6374325',
'invoiceTitle' => 'Monthly',
'invoiceStatus' => 'Paid',
'accountId' => '6235218753',
'totalExVat' => 208.95,
'dateCreated' => '1 May 2012',
'vatAmount' => 25.00
),
);
$sumDetail = 'vatAmount';
$totalVAT = array_reduce($account_invoices,
function($runningTotal, $record) use($sumDetail) {
$runningTotal += $record[$sumDetail];
return $runningTotal;
},
0
);
echo $totalVAT;
Answer 6:
为此,您可以使用array_map()
并选择vatAmount
第一列:
$totalVatAmount = array_sum(array_map(function($account_invoices) {
return $account_invoices['vatAmount'];
}, $account_invoices));
当然,这在内部执行双环流; 它只是你没有看到它里面的代码。 如果你使用array_reduce()
那么你就可以摆脱一个循环:
$totalVatAmount = array_reduce($account_invoices,
function($totalAmount, $item) {
$totalAmount += $item['vatAmount'];
return $totalAmount;
},
0
);
然而,如果速度是唯一感兴趣的,你应该使用foreach
。 因为用于计算最后的和没有函数调用。 该解决方案比其他解决方案快。
$totalVatAmount = 0;
foreach ($account_invoices as $item) {
$totalVatAmount += $item['vatAmount'];
}
Answer 7:
你不能直接这样做array_sum
,这将总结在阵列中的一切。
你可以用一个循环做到这一点:
$sum = 0;
foreach($items as $item)
$sum += $item['vatAmount'];
或者你可以过滤阵列(在这种情况下, 它是不是很方便 ,但如果你要计算每个单项,然后总和......,比方说,S&H费用加增值税加上...):
// Input: an array (element #n of array of arrays), output: VAT field
function getVAT($item)
{
return $item['vatAmount'];
}
// Array with all VATs
$vats = array_map('getVAT', $items);
$sum = array_sum($vats);
Answer 8:
你也可以做到这一点(如果你喜欢array_sum功能):
foreach($account_invoices as $num => $values) {
$vatAmount[] = $values[ 'vatAmount' ];
}
$Total = array_sum($vatAmount);
Answer 9:
只是另一种方式来做到这一点使用array_reduce:
$vatMount = array_reduce($account_invoices, function($total, $value) {
return $total + $value['vatAmount'];
});
文章来源: multidimensional array array_sum