开发者

What's the most elegant way to add up multidimensional arrays field by field in PHP?

I'm trying to add up two multidimensional arrays, both equally sized, field by field. I.e.:

$sum[4][3] = $a[4][3] + $b[4][3];

Or:

$a = array( array(1, 4), array(3, 2));
$b = array( array(9, 2), array(1, 0));

Should result in:

$sum = array( array(10, 6), array开发者_开发技巧(4, 2));

Is there a more elegant way than foreaching over all the arrays?


You can use the function array_map() This applies a function to each of the elements in an array ($a in your case) and applies a callback function to those, you can give extra arguments to those functions by supplying another array ($b in your case). The result will be $sum of your example.

The callback function would need to check if the arguments are arrays, if so it would need to do the mapping function again (so its a recursive function) if the arguments aren't an array it needs to add the function.

http://nl3.php.net/manual/en/function.array-map.php

So all in all you'd be off much better doing a nested foreach :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜