通过索引键聚合多维数组的优雅方法
如何递归地找到看起来像这样的数组的所有子项的总价值?
[0] => Array
(
[value] => ? // 8590.25 + 200.5 + 22.4
[children] => Array
(
[0] => Array
(
[value] => ? // 8590.25 + 200.5
[children] => Array
(
[0] => Array
(
[value] => 8590.25 // leaf node
)
[1] => Array
(
[value] => 200.05 // leaf node
)
)
)
[1] => Array
(
[value] => 22.4 // leaf node
)
)
)
How can I recursively find the total value of all children of an array that looks something like this?
[0] => Array
(
[value] => ? // 8590.25 + 200.5 + 22.4
[children] => Array
(
[0] => Array
(
[value] => ? // 8590.25 + 200.5
[children] => Array
(
[0] => Array
(
[value] => 8590.25 // leaf node
)
[1] => Array
(
[value] => 200.05 // leaf node
)
)
)
[1] => Array
(
[value] => 22.4 // leaf node
)
)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,我会使用类而不是数组。这样,您就可以使用 getValue () 方法(或使用 magic 来使用 __get 定义 value 属性),根据需要对子值求和。如果您保证事情在某个点之后不会发生变化,则可以缓存这些子总和以避免重复计算。也许是这样的?
This is the kind of case where I'd use a class instead of an array. That way, you can have a getValue () method (or use magic to define the value property using __get), that sums the child values on demand. If you have guarantees that things won't change after a point, you can cache those child sums to avoid repetetive computations. Maybe something like this?
这将为您提供叶节点值的总和:
相当于使用匿名函数(PHP 5.3+):
This will give you the total sum of the leaf node values:
Equivalent using anonymous functions (PHP 5.3+):