121, "name" => "Some Name 1"-6ren">
gpt4 book ai didi

php - 在分组时按数字键和列值求和合并深层行组

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:53:22 24 4
gpt4 key购买 nike

我有以下数组,需要通过求和内部值来减少它。

输入:

$array = [
[
121 => [ "number" => 121, "name" => "Some Name 1", "value" => "2.222" ],
116 => [ "number" => 116, "name" => "Some Name 2", "value" => "1.111" ],
1 => [ "number" => 1, "name" => "Some Name 3", "value" => "1.232" ]
],
[
121 => [ "number" => 121, "name" => "Some Name 1", "value" => "1.111" ],
116 => [ "number" => 116, "name" => "Some Name 2", "value" => "2.222" ],
1 => [ "number" => 1, "name" => "Some Name 3", "value" => "3.111" ]
]
];

期望的结果:

0 => array:116 [
121 => array:3 [
"number" => 121
"name" => "Some Name 1"
"value" => "3.333"
]
116 => array:3 [
"number" => 116
"name" => "Some Name 2"
"value" => "3.333"
]
1 => array:3 [
"number" => 1
"name" => "Some Name 3"
"value" => "4.343"
]
]

假设输入数组的长度未定义,但复杂度/嵌套级别最大为 2,那么根据输入计算结果数组的高效/有效方法是什么。

我正在寻找针对 PHP5.6 和 PHP7+ 的性能优化解决方案。

最佳答案

使用嵌套循环访问深层子数组。当您迭代时,将首先遇到的行插入结果数组,同时保留它们的数字/关联键。使用这些键来确定(在循环时)以确定之前是否遇到过一行——如果遇到过,只需将 value 值添加到缓存的行。

代码:(Demo)

$result = [];
foreach ($array as $group) {
foreach ($group as $key => $row) {
if (!isset($result[$key])) {
$result[$key] = $row;
} else {
$result[$key]['value'] += $row['value'];
}
}
}
var_export($result);

关于php - 在分组时按数字键和列值求和合并深层行组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44447726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com