【问题标题】:How to group subarray data using multiple column values and individually sum the remaining column values?如何使用多个列值对子数组数据进行分组并单独对剩余的列值求和?
【发布时间】:2017-11-15 01:59:09
【问题描述】:

如何按来源和日期分组,然后在下面的数组中 SUM 浏览量和收入

Array
(
    [0] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Google
            [visits] => 6000
            [Pageviews] => 12,214
            [Revenue] => 25
        )
    [1] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Google
            [visits] => 600
            [Pageviews] => 1015
            [Revenue] => 10
        )
    [2] => Array
          (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Facebook
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 40
        )

    [3] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Google
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 10
        )

    [4] => Array
         (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Facebook
            [visits] => 1600
            [Pageviews] => 11,445
            [Revenue] => 5
        )
     [5] => Array
         (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Facebook
            [visits] => 700
            [Pageviews] => 7,445
            [Revenue] => 8
        )
)

预期结果

Array
(
    [0] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Google
            [visits] => 6600
            [Pageviews] => 13,229
            [Revenue] => 35
        )
    [1] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Facebook
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 40
        )
    [2] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Google
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 10
        )
    [3] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Facebook
            [visits] => 2,300
            [Pageviews] => 18,890
            [Revenue] => 35
        )
) 

【问题讨论】:

  • 代码在哪里,这是来自 DB 的吗?为什么不从那里总结它们
  • StackOverflow 上的用户会在在你帮助自己之后帮助你。做一些研究:meta.stackoverflow.com/q/261592/1011527。了解如何发布好问题:stackoverflow.com/help/how-to-ask。还有stackoverflow.com/help/mcve.
  • 请使用 var_export() 而不是 print_r 或 var_dump 发布您的问题。否则,我们必须编写代码来在我们的测试系统上创建数组来帮助您。大多数人根本不会打扰。
  • 它不在数据库中,它来自 API。
  • 您打算如何区分每个数组中的两个Source 元素?

标签: php arrays multidimensional-array sum grouping


【解决方案1】:

这是您需要的功能。干杯...

function combineAndSumUp ($myArray = []) {

    $finalArray = Array ();

    foreach ($myArray as $nkey => $nvalue) {

        $has = false;
        $fk = false;

        // Remove comma from numbers
        $nvalue['Pageviews'] = str_replace(",","",$nvalue["Pageviews"]);

        foreach ($finalArray as $fkey => $fvalue) {
            if ( ($fvalue['Date'] == $nvalue['Date']) && ($fvalue['Source'] == $nvalue['Source']) ) {
                $has = true;
                $fk = $fkey;
                break;
            }
        }

        if ( $has === false ) {
            $finalArray[] = $nvalue;
        } else {
            $finalArray[$fk]['visits'] += $nvalue['visits'];
            $finalArray[$fk]['Pageviews'] += $nvalue['Pageviews'];
            $finalArray[$fk]['Revenue'] += $nvalue['Revenue'];
        }

    }

    return $finalArray;
}

【讨论】:

    【解决方案2】:

    @J.D.Pace 的评论是什么意思:

    您打算如何区分每个数组中的两个 Source 元素?

    是……

    “您的传入数据是不可能的,因为您可能在同一级别的数组中没有两个相同的键。您的数据在同一子数组中显示 "Source" => "Analytics""Source" => "Facebook"。” ...这意味着您的样本输入数据不准确。

    因为我们不知道在您的情况下应该如何 并且因为Analytics 值对于这项任务完全没有价值,我将提供一个忽略这些不准确子数组元素的解决方案。

    其他答案是工作太辛苦,写了太多代码。无需编写多个/嵌套循环,也无需对数据进行预排序。通过在输出数组中分配“复合临时键”并在处理时将输出数组用作“查找数组”,只需一个循环即可完成此任务。 isset() 是一种非常快速的方法,可以确定当前子数组是否包含新的数据组或之前是否遇到过该组。

    完成后,您可以选择调用array_values() 来重新索引输出(如果需要)。您可能还想重新迭代以重新格式化页面浏览量以包含逗号 - 这再次由您自行决定。

    代码:(Demo)

    $array = [
        ['Date' => '2017-10-31', 'Source' => 'Google', 'visits' => '6000', 'Pageviews' => '12,214', 'Revenue' => '25'],
        ['Date' => '2017-10-31', 'Source' => 'Google', 'visits' => '600', 'Pageviews' => '1015', 'Revenue' => '10'],
        ['Date' => '2017-10-31', 'Source' => 'Facebook', 'visits' => '600', 'Pageviews' => '1144', 'Revenue' => '40'],
        ['Date' => '2017-10-30', 'Source' => 'Google', 'visits' => '600', 'Pageviews' => '1144', 'Revenue' => '10'],
        ['Date' => '2017-10-30', 'Source' => 'Facebook', 'visits' => '1600', 'Pageviews' => '11,445', 'Revenue' => '5'],
        ['Date' => '2017-10-30', 'Source' => 'Facebook', 'visits' => '700', 'Pageviews' => '7,445', 'Revenue' => '8'],
    ];
    
    foreach ($array as $subarray) {
        $tempKey = $subarray['Source'].$subarray['Date'];  // this is the compound value
        $subarray['Pageviews'] = str_replace(',', '', $subarray['Pageviews']); // get rid of meddlesome comma
        if (isset($result[$tempKey])) {
            $result[$tempKey]['visits'] += $subarray['visits'];
            $result[$tempKey]['Pageviews'] += $subarray['Pageviews'];
            $result[$tempKey]['Revenue'] += $subarray['Revenue'];
        } else {
            $result[$tempKey] = $subarray;
        }
    }
    var_export(array_values($result));
    

    输出:(删节)

    array (
      0 => 
      array (
        'Date' => '2017-10-31',
        'Source' => 'Google',
        'visits' => 6600,
        'Pageviews' => 13229,
        'Revenue' => 35,
      ),
      ...
    )
    

    【讨论】:

      【解决方案3】:

      假设只有一个Source 索引。

      试试这个:

      array_multisort(array_column($arr, 'Date'), SORT_DESC,array_column($arr, 'Source'), SORT_DESC, $arr);
      
      $new_arr = [];
      $temp = ["Date"=>""];
      $ctr = 0;
      foreach($arr as $val) {
          if($val["Date"] == $temp["Date"] && $val["Source"] == $temp["Source"]) {
              $ctr2 = $ctr - 1;
              $new_arr[$ctr2]["visits"] += $val["visits"];
              $new_arr[$ctr2]["Pageviews"] += $val["Pageviews"];
              $new_arr[$ctr2]["Revenue"] += $val["Revenue"];
          } else {
              $new_arr[$ctr++] = $val;
          }
          $temp = $val;
      }
      
      print_r($new_arr);
      

      【讨论】:

        猜你喜欢
        • 2021-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-19
        相关资源
        最近更新 更多