[英]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). 您可以使用函数array_map()将此函数应用于数组中的每个元素(以您的情况为$ a),并将回调函数应用于这些元素,可以通过提供另一个数组($ b)为这些函数提供额外的参数在您的情况下)。 The result will be $sum of your example. 结果将是您的示例的$ sum。
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 http://nl3.php.net/manual/en/function.array-map.php
So all in all you'd be off much better doing a nested foreach :) 所以总的来说,做一个嵌套的foreach会更好:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.