Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/239.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中将值添加到数组时执行值添加_Php - Fatal编程技术网

在PHP中将值添加到数组时执行值添加

在PHP中将值添加到数组时执行值添加,php,Php,我有来自数据库的值,试图用初始值添加下一个值,然后插入到数组中,有人能在这里帮助我吗 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) { $balance[] = (round($row["Balance"], 2))++;; } 情景: 我有1,2,3,4,5值 我希望将这些值放入数组,如下所示: {1,3,6,10,15} 即: {1, (1+2), (1+2+3), (1+2+

我有来自数据库的值,试图用初始值添加下一个值,然后插入到数组中,有人能在这里帮助我吗

while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {   
        $balance[]  =   (round($row["Balance"], 2))++;;
    }
情景:

我有
1,2,3,4,5
值 我希望将这些值放入数组,如下所示:

{1,3,6,10,15}
即:

{1, (1+2), (1+2+3), (1+2+3+4), (1+2+3+4+5)}

有人有什么想法吗?

你最好有一个连续的总数,然后把它加在

$total = 0;
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {  
    $total = round($row["Balance"], 2) + $total;
    $balance[]  = $total;
}
也许:

$a = [1,2,3,4,5];

$b = [];

foreach($a as $c) {
    if(count($b) === 0) {
        $b[] = $c;
    } else {
        $b[] = end($b) + $c;
    }
}
$b
是结果