简体   繁体   中英

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. Ie:

$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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM