简体   繁体   English

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

[英]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.

相关问题 从包含元素的键的值枚举多维PHP数组上的键的最优雅方法是什么? - What's the most elegant way to enumerate keys on a multidimensional PHP array from the value of a contained element's key? 在PHP中按字段分组多维数组 - Grouping multidimensional arrays in PHP by field 以数学方式添加两个多维数组的最有效方法? - Most efficient way to mathematically add two multidimensional arrays? PHP中“foreach x除了y”最优雅的方法是什么? - What is the most elegant way to do “foreach x except y” in PHP? 检索MySQL表注释的最优雅方法是什么? - What's the most elegant way to retrieve a MySQL table comment? 在PHP中定义全局常量数组的最“优雅”方法是什么 - What is the most “elegant” way to define a global constant array in PHP 什么是加快 PHP 中 XML 的加载/处理的优雅方法? - What is an elegant way to speed up the loading/processing of XML in PHP? 用php访问数组元素中的字段的正确方法是什么? - What's the correct way to access a field in an array element with php? PHP:将大型数组汇总为10个数组的最有效方法是什么? - PHP: What's the most efficient way to summarize a large array into just 10 arrays? PHP中从两个并行索引数组创建关联数组的最简单方法是什么? - What's the most straightforward way in PHP to create an associative array from two parallel indexed arrays?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM