dongyouzhi7218 2010-01-29 10:24
浏览 71
已采纳

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

  • 写回答

1条回答 默认 最新

  • dongraa1986 2010-01-29 10:51
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题
  • ¥15 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信
  • ¥15 改进Yolov8时添加的注意力模块在task.py里检测不到
  • ¥50 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错