PHP中的数组求和和和计数行

PHP中的数组求和和和计数行,php,arrays,count,sum,array-sum,Php,Arrays,Count,Sum,Array Sum,我有一个函数getData,它返回: array:4 [▼ 0 => array:1 [▼ 0 => "5689.01" ] 1 => array:1 [▼ 0 => "5689.01" ] 2 => array:1 [▼ 0 => "0.0" ] 3 => array:1 [▼ 0 => "5665.11" ] ] 我需要使用每次触发调用时返回的值计算行数(这次是4行,

我有一个函数getData,它返回:

    array:4 [▼
  0 => array:1 [▼
    0 => "5689.01"
  ]
  1 => array:1 [▼
    0 => "5689.01"

  ]
  2 => array:1 [▼
    0 => "0.0"
  ]
  3 => array:1 [▼
    0 => "5665.11"
   ]
]
我需要使用每次触发调用时返回的值计算行数(这次是4行,如上所述),并返回所列的所有结果的总和

 $rows = $this->get('app')->getData();

 if($rows) {
        foreach ($rows as $row) {
            $sumOfAll = 0;
            $total = count($rows);
            $sumOfAll += array_sum(array($row[0] * $total));

            dump($sumOfAll);die;
    }
}

我总是得到一个错误的总和,在本例中是22756.04。

要修正你的总和值,你需要将
$sumOfAll
变量移出你的
foreach

从以下位置更改代码:

foreach ($rows as $row) {
    $sumOfAll = 0;
    $total = count($rows);
    $sumOfAll += array_sum(array($row[6] * $total));

    dump($sumOfAll);die;
}
为此:

$sumOfAll = 0;
foreach ($rows as $row) {
    $total = count($rows);
    $sumOfAll += array_sum(array($row[6] * $total));
}
dump($sumOfAll);die;

要修正求和值,需要将
$sumOfAll
变量移出
foreach

从以下位置更改代码:

foreach ($rows as $row) {
    $sumOfAll = 0;
    $total = count($rows);
    $sumOfAll += array_sum(array($row[6] * $total));

    dump($sumOfAll);die;
}
为此:

$sumOfAll = 0;
foreach ($rows as $row) {
    $total = count($rows);
    $sumOfAll += array_sum(array($row[6] * $total));
}
dump($sumOfAll);die;

使用array_sum和array_列获取值并求和。
然后使用count()获取计数

$sum = array_sum(array_column($arr, 0));
$count = count($arr);

echo "count is ". $count . " And sum is " . $sum;

使用array\u sum和array\u列获取值并求和。
然后使用count()获取计数

$sum = array_sum(array_column($arr, 0));
$count = count($arr);

echo "count is ". $count . " And sum is " . $sum;

$sumOfAll=array\u sum(array\u column($rows,6))*count($rows)
@splash58
6
这是从哪里得到的?它与您的上一个问题相同()请避免此问题-如果上一个问题不相关,请删除itI,我应该对其进行编辑。谢谢@dWinder
$sumOfAll=array\u和(array\u列($rows,6))*计数($rows)
@splash58
6
这是从哪里得到的?它与您的上一个问题相同()请避免此问题-如果上一个问题不相关,请删除itI,我应该对其进行编辑。谢谢@你提供了一个适合我的答案。多谢各位@Andreas@JohnMartin没问题,请随意接受答案,以便功能访问者了解您喜欢哪种方法。您提供了一个适合我的答案。多谢各位@Andreas@JohnMartin没问题,请随意接受答案,以便功能访问者看到您喜欢的方法