PHP总和数组值基于另一个数组中的文本重复项 [英] PHP sum array value based on textual duplicate in another array

查看:38
本文介绍了PHP总和数组值基于另一个数组中的文本重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组,两个数组的计数长度始终相同.一个具有与整数混合的双精度,第二个具有文本(仅字符串)值.它们确实相关,所以我需要它们都保持顺序.很抱歉,没有按键可以使用(按设计).

I have two arrays, both will always be the same count length. One has doubles mixed with integers, the second has textual (string only) values. They do correlate so I need them both to stay in order. Sorry no keys to work with (by design).

我需要对具有字符串的数组中重复项的值求和.

I need to sum the values where I have duplicates in the array that has strings.

示例

$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");

所以我的算法之后应该像这样

So my algorithm should look like this after

$dataLabelGraph = array(21.86, 8, 1, 0.5);
$dataCalcGraph = array("Coding", "Web development - Coding", "Meeting", "Content");

我正试图从马丁D. @"https://stackoverflow.com/a/22071693/12835769">https://stackoverflow.com/a/22071693/12835769

I was trying to adapt this solution, from the awesome brain of 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);

给出类似的结果,这很接近,但是我需要它们保留在两个单独的数组中

Gives something like this, which is close but I need them to remain in two separate arrays

array (size=4)
  'Coding' => float 21.86
  'Web development - Coding' => int 8
  'Meeting' => int 1
  'Content' => float 0.5

任何帮助我克服困境的方法都将大有帮助.荣誉.

Any help to get me over the line would be immensely helpful. Kudos.

推荐答案

按名称"分组并在您迭代时求和.循环结束后,将键和值拆分为单独的数组.

Group by the "name" and sum as you iterate. When the loop is finished, split the keys and the values into separate arrays.

代码:(演示)

$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,
)

这篇关于PHP总和数组值基于另一个数组中的文本重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆