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

数组累计求和?

WBOY
Release: 2016-06-06 20:24:06
Original
1565 people have browsed it

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

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

要求输出

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

</code>
Copy after login
Copy after login

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

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

回复内容:

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

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

要求输出

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

</code>
Copy after login
Copy after login

也即:新输出的数组的每一项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>
Copy after login

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>
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template