Home >Backend Development >PHP Tutorial >数组累计求和?

数组累计求和?

WBOY
WBOYOriginal
2016-06-06 20:24:061560browse

HI,我遇到一个需求,现在有个数组

<code>$old=[1,2,3]
</code>

要求输出

<code>$new=[1,3,6]

</code>

也即:新输出的数组的每一项N,都是于此对应的老数组的前N项和(包括N),那么,有什么好的办法呢?

ps :代码能最好优雅一点~

回复内容:

HI,我遇到一个需求,现在有个数组

<code>$old=[1,2,3]
</code>

要求输出

<code>$new=[1,3,6]

</code>

也即:新输出的数组的每一项N,都是于此对应的老数组的前N项和(包括N),那么,有什么好的办法呢?

ps :代码能最好优雅一点~

<code>var arr = [1, 2, 3, 4, 5];
var newArr = [];
arr.reduce(function (prev, next) {
    newArr.push(prev + next);
    return prev + next;
}, 0);
</code>

php找相应的reduce方法

用php写出来的,感觉有点笨,不够优雅

<code>$arr = array(1,2,3,4,5,6);
$arr1 = array();
foreach ($arr as $key=>$val) {
    $arr2 = array_slice($arr, 0, $key+1);
    $arr1[] = array_reduce($arr2, function($v, $w){
        $v += $w;
        return $v;
    });
}
print_r($arr1);</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn