我有两个数组,它们的计数长度总是相同的。一个是双精度数与整数混合,第二个是文本值(仅限字符串)。它们确实是相关的,所以我需要它们都保持有序。对不起,没有钥匙可用(根据设计)。
我需要对包含字符串的数组中有重复项的值求和。
示例
$dataLabelGraph = array(3, 8, 1, 4.85, 1, 0.5, 6.01, 7);
$dataCalcGraph = array("Coding", "Web development - Coding", "Meeting", "Coding", "Coding", "Content", "Coding", "Coding");
所以我的算法应该如下所示
$dataLabelGraph = array(21.86, 8, 1, 0.5);
$dataCalcGraph = array("Coding", "Web development - Coding", "Meeting", "Content");
我试着从Martin D. @ https://stackoverflow.com/a/22071693/12835769这个令人惊叹的大脑中改编这个解决方案
$records_array = array("Coding", "Web development - Coding", "Meeting", "Coding", "Coding", "Content", "Coding");
$quantities_array = array(3, 8, 1, 4.85, 1, 0.5, 6.01, 7);
$new_array = array();
foreach ($records_array as $record_position => $new_array_key){
$new_array[$new_array_key] += $quantities_array[$record_position];
}
var_dump($new_array);
如下所示,它很接近,但我需要它们保留在两个单独的数组中
array (size=4)
'Coding' => float 21.86
'Web development - Coding' => int 8
'Meeting' => int 1
'Content' => float 0.5
任何帮助我越过这条线的帮助都将是非常有帮助的。太棒了。
发布于 2020-10-19 17:38:44
按"name“分组,并在迭代时求和。循环完成后,将键和值拆分为单独的数组。
代码:(Demo)
$records = [
"Coding",
"Web development - Coding",
"Meeting",
"Coding",
"Coding",
"Content",
"Coding",
"Coding"
];
$quantities = [
3,
8,
1,
4.85,
1,
0.5,
6.01,
7
];
$result = [];
foreach ($records as $index => $label){
$result[$label] = ($result[$label] ?? 0) + $quantities[$index];
}
var_export(array_keys($result));
var_export(array_values($result));
输出:
array (
0 => 'Coding',
1 => 'Web development - Coding',
2 => 'Meeting',
3 => 'Content',
)
array (
0 => 21.86,
1 => 8,
2 => 1,
3 => 0.5,
)
https://stackoverflow.com/questions/64422650
复制相似问题