做array_sum的更简单方法?

时间:2018-12-24 08:25:59

标签: php arrays array-sum

我正在使用的代码对我来说很好用。我目前遇到的问题更多是一种更简单的方法来执行我要执行的操作。我为需要求和成最终总值的每个数组创建了变量。有没有办法让我不必在数组中有那么多变量?

这是我目前拥有的东西,我认为它可以完成工作,但看起来像胡扯。许多变量的方式。

$a1 = $aDataTableDetailHTML[0]['Players'];
$a2 = $aDataTableDetailHTML[1]['Players'];
$a3 = $aDataTableDetailHTML[2]['Players'];
$a4 = $aDataTableDetailHTML[3]['Players'];
$a5 = $aDataTableDetailHTML[4]['Players'];
$a6 = $aDataTableDetailHTML[5]['Players'];
$a7 = $aDataTableDetailHTML[6]['Players'];
$a8 = $aDataTableDetailHTML[7]['Players'];
$a9 = $aDataTableDetailHTML[8]['Players'];
$a10 = $aDataTableDetailHTML[9]['Players'];
$a11 = $aDataTableDetailHTML[10]['Players'];
$a12 = $aDataTableDetailHTML[11]['Players'];
$a13 = $aDataTableDetailHTML[12]['Players'];
$a14 = $aDataTableDetailHTML[13]['Players'];
$a15 = $aDataTableDetailHTML[14]['Players'];
$a16 = $aDataTableDetailHTML[15]['Players'];
$a17 = $aDataTableDetailHTML[16]['Players'];
$a18 = $aDataTableDetailHTML[17]['Players'];
$a19 = $aDataTableDetailHTML[18]['Players'];
$a20 = $aDataTableDetailHTML[19]['Players'];
$a21 = $aDataTableDetailHTML[20]['Players'];
$a22 = $aDataTableDetailHTML[21]['Players'];
$a23 = $aDataTableDetailHTML[22]['Players'];
$a24 = $aDataTableDetailHTML[23]['Players'];
$a25 = $aDataTableDetailHTML[24]['Players'];
$a26 = $aDataTableDetailHTML[25]['Players'];
$a27 = $aDataTableDetailHTML[26]['Players'];
$a28 = $aDataTableDetailHTML[27]['Players'];
$a29 = $aDataTableDetailHTML[28]['Players'];
$a30 = $aDataTableDetailHTML[29]['Players'];
$a31 = $aDataTableDetailHTML[30]['Players'];
$a32 = $aDataTableDetailHTML[31]['Players'];
$totalplayers = array($a1, $a2, $a3, $a4, $a5, $a6, $a7, $a8, $a9, $a10, $a11, $a12, $a13, $a14, $a15, $a16, $a17, $a18, $a19, $a20, $a21, $a22, $a23, $a24, $a25, $a26, $a27, $a28, $a29, $a30, $a31, $a32);
$value = array_sum($totalplayers);

3 个答案:

答案 0 :(得分:3)

根据@PaulCrovella在我的原始帖子中的评论,我提出了一些很棒的东西。

$values = array_column($aDataTableDetailHTML, 'Players');
$total = array_sum($values);
print_r($total);

答案 1 :(得分:2)

使用foreach 4 行而不是 34 行)的普通方法:

$sum = 0;
foreach ($aDataTableDetailHTML as $item) {
    $sum += $item['Players'];
}

答案 2 :(得分:1)

echo array_sum(array_column($aDataTableDetailHTML, 'Players'));