添加数组 [英] Adding arrays
问题描述
考虑以下多维数组:
---------------------------
$ arr =数组(
数组(3,5,7,9),
数组(2,4,6,8),>
数组(1,3,5,7)
);
函数add_arrays($ arr){
for($ row = 0; $ row< count($ arr [0]); $ row ++){
for($ column = 0; $ column< count($ arr [ $ column]); $ column ++){
$ totals [$ row] = $ totals [$ row] + $ arr [$ column] [$ row];
}
}
print_r($ totals);
}
add_arrays($ arr) ;
---------------------------
返回以下数组:
数组([0] = 6 [1] = 12 [2] = 18 [3] = 24)
这些是数组的总数在$ arr:6(3 + 2 + 1,添加所有
第一个元素),12(5 + 4 + 3,添加所有第二个元素)等等。这个
花了我一天的时间来构建;)但是,我会像add_arrays一样返回一个亩的
像这样的ltidimensional数组:
数组(
数组([0] = 3 [1] = 5 [2] = 7 [3] = 9) //第1行
数组([0] = 5 [1] = 9 [2] = 13 [3] = 17)//第1行+第2行
行(即5 = 3 + 2)
数组([0] = 6 [1] = 12 [2] = 18 [3] = 24)// 1st _ 2nd + 3rd
行(即6 = 3 + 2 + 1)
)
有人可以帮我构建一个功能吗?>
将一行添加到前一行并将结果添加到输出
数组?任何帮助都会非常感激!
arr = array(
array(3,5, 7,9),
数组(2,4,6,8),
数组(1,3,5,7)
);
函数add_arrays(
arr){
for(
< blockquote> row = 0;
Consider the following multi-dimensional array:
---------------------------
$arr = array(
array(3, 5, 7, 9),
array(2, 4, 6, 8),
array(1, 3, 5, 7)
);
function add_arrays($arr) {
for ($row = 0; $row < count($arr[0]); $row++) {
for ($column = 0; $column < count($arr[$column]); $column++) {
$totals[$row] = $totals[$row] + $arr[$column][$row];
}
}
print_r($totals);
}
add_arrays($arr);
---------------------------
This returns the following array:
Array ( [0] =6 [1] =12 [2] =18 [3] =24 )
These are the totals of the array''s in $arr: 6 (3 + 2 + 1, added all
first elements), 12 (5 + 4 + 3, added all second elements), etc. This
took me quite a portion of the day to construct ;) However, I would
like add_arrays to return a multidimensional array like this:
Array (
Array ( [0] =3 [1] = 5 [2] = 7 [3] = 9 ) // 1st row
Array ( [0] =5 [1] = 9 [2] =13 [3] =17 ) // 1st row + second
row (i.e. 5 = 3 + 2)
Array ( [0] =6 [1] =12 [2] =18 [3] =24 ) // 1st _ 2nd + 3rd
row (i.e. 6 = 3 + 2 + 1)
)
Could somebody please help me building a function that does just that?
Adding one row to the previous one and adding the result to the output
array? Any help would be greatly apprectiated!
arr = array(
array(3, 5, 7, 9),
array(2, 4, 6, 8),
array(1, 3, 5, 7)
);
function add_arrays(
arr) {
for (
row = 0;
这篇关于添加数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!