简体   繁体   English

将分组元素添加到 2d 数组并在各自组中求和值

[英]Add grouping elements to 2d array and sum values in respective group

I need to add new elemets to my array when a new category value is encountered.当遇到新的category值时,我需要将新的元素添加到我的数组中。 When a category value is encountered after the first time, its value1 and value2 values should be added to the first encounter's respective values.当第一次遇到category值时,应将其value1value2值添加到第一次遇到的各自值中。

Also, in the result array, I no longer wish to keep the category column.此外,在结果数组中,我不再希望保留category列。 The category-grouping rows should use the category value as its name value.类别分组行应使用category值作为其name值。

Sample input:示例输入:

$datas = [
    [
        'category' => 'Solution',
        'name' => 'Name1',
        'value1' => 20,
        'value2' => 21
    ],
    [
        'category' => 'Solution',
        'name' => 'Name2',
        'value1' => 30,
        'value2' => 31
    ],
    [
        'category' => 'Solution1',
        'name' => 'Name3',
        'value1' => 40,
        'value2' => 41
    ]
];

Desired result:期望的结果:

[
    ['name' => 'Solution',  'value1' => 50, 'value2' => 52],
    ['name' => 'Name1',     'value1' => 20, 'value2' => 21],
    ['name' => 'Name2',     'value1' => 30, 'value2' => 31],
    ['name' => 'Solution1', 'value1' => 40, 'value2' => 41],
    ['name' => 'Name3',     'value1' => 40, 'value2' => 41]
]

I tried like this:我试过这样的:

private function groupByProductSuperCategory($datas)
{
    $return = [];
    foreach ($datas as $data) {
        $return[$data['category']][$data['name']] = array_sum(array_column('category', $data);
    }
    return $return;
}

The idea is to calculate first all sum values for by category, and after that just put values from name like another array.这个想法是首先按类别计算所有总和值,然后像另一个数组一样将名称中的值放入。 Have you an idea of how to do that?你知道怎么做吗?

From the posted array... To end in the desired array, there is some tiny fixes to do first. 从发布的数组中开始...要以所需的数组结尾,首先需要进行一些小的修复。 But I assumed it was due to typos while copying here... 但是我认为这是由于在这里复制时出现错别字...

So here is the array I started with: 所以这是我开始的数组:

$result = [
  0 => [
    "category"   => 'Solution',
    "name"       => 'Name1',
    "value1"     => 20,
    "value2"     => 21
  ],
  1 => [
    "category"   => 'Solution',
    "name"       => 'Name2',
    "value1"     => 30,
    "value2"     => 31
  ],
  2 => [
    "category"   => 'Solution1',
    "name"       => 'Name3',
    "value1"     => 40,
    "value2"     => 41
  ]
];

Now, that re-organization of the data is a bit more complex than it looks... You need to perform several loops to: 现在,数据的重组比看起来要复杂一些。您需要执行几个循环以:

  • Find distinct "category" names 查找不同的“类别”名称
  • Perform the summations for each 对每个执行求和
  • Add the sum item and the single items 添加总和项和单个项

So here is the code I ended with: 所以这是我结尾的代码:

function groupByProductSuperCategory($datas){
  $category = [];
  $return = [];

  // Find distinct categories
  foreach ($datas as $data) {
    if(!in_array($data["category"],$category)){
      array_push($category,$data["category"]);
    }
  }

  // For each distinct category, add the sum item and the single items
  foreach ($category as $cat) {

    // Get the sums
    if(!in_array($cat,$return)){

      $sum1 = 0;
      $sum2 = 0;
      foreach ($datas as $data) {
        if($data["category"] == $cat){
          $sum1 += $data["value1"];
          $sum2 += $data["value2"];
        }
      }
    }

    // Push the sums in the return array
    array_push($return,[
      "name" => $cat,
      "value1" => $sum1,
      "value2" => $sum2,
    ]);

    // Push the single elements
    foreach ($datas as $data) {
      if($cat == $data["category"]){
        array_push($return,[
          "name" => $data["name"],
          "value1" => $data["value1"],
          "value2" => $data["value2"],
        ]);
      }
    }


  }

  return $return;

}

Here is a PHPFiddle to try it out... Hit [F9] to run. 这是一个PHPFiddle可以尝试的...点击[F9]运行。

It is much more direct, efficient, and readable to implement a single loop and push reference variables into the result array to allow summing based on shared categories without keeping track of the actual indexes of the category rows.实现单个循环并将引用变量推入结果数组以允许基于共享类别进行求和而无需跟踪类别行的实际索引会更加直接、高效和可读。

Code: ( Demo )代码:(演示

$result = [];
foreach ($array as $row) {
    if (!isset($ref[$row['category']])) {
        $ref[$row['category']] = [
            'name' => $row['category'],
            'value1' => 0,
            'value2' => 0
        ];
        $result[] = &$ref[$row['category']];
    }
    $ref[$row['category']]['value1'] += $row['value1'];
    $ref[$row['category']]['value2'] += $row['value2'];
    unset($row['category']);
    $result[] = $row;
}
var_export($result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM