按列求和PHP数组

时间:2019-03-19 16:18:15

标签: php arrays php-7

我有这个数组:

$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
   ]
]

我想要一个数组:

$new_array = [
    0 => [
        name    => 'Solution',
        value1  => 50   // sum of array with key = 0 and key = 1
        value2  => 52
    ], 
    1 => [
        name    => 'Name1'
        value1  => 20,
        value2  => 21
    ],
    2 => [
        name    => 'Name2',
        value1  => 30,
        value2  => 31
    ],
    3 => [
        name    => 'Solution1',
        value1  => 40,
        value2  => 41
    ],
    4 => [
        name    => 'Name3',
        value1  => 40,
        value2  => 41
    ]
]

我尝试过这样:

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

想法是首先计算类别的所有总和值,然后再像其他数组一样输入名称中的值。您知道如何执行此操作吗?请帮助我。

1 个答案:

答案 0 :(得分:0)

从发布的数组中开始...要以所需的数组结尾,首先需要进行一些小的修复。但我认为这是由于在此处复制时出现错别字...

这是我开始的数组:

$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
  ]
];

现在,数据的重组比看起来要复杂一些……您需要执行几个循环来:

  • 找到不同的“类别”名称
  • 对每一个进行求和
  • 添加总和项和单个项

这是我结尾的代码:

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;

}

这里有一个PHPFiddle可以尝试...点击[F9]运行。