在PHP中逐字段添加多维数组的最优雅方法是什么?

在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?

我正在尝试按字段添加两个大小相同的多维数组。 即: p>

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

或者: p>

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

应该导致: p>

   $ sum = array(array(10,6),array(4,2)); 
  code>  pre> 
 
 

是否有比foreed更优雅的方式 数组? p> div>

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