简体   繁体   English

在php中重新组合和求和数组

[英]Regroup and sum array in php

I collect a start and end date from my db.我从我的数据库中收集开始和结束日期。 I use a function to determine a value per day.我使用一个函数来确定每天的价值。

$array = array();
       foreach ($db_value as $key => $value) {

      $Variable1 = strtotime($Date1);
      $Variable2 = strtotime($Date2);

      for ($currentDate = $Variable1; $currentDate <= $Variable2;
                                      $currentDate += (86400)) {

      $Store = date('Y-m-d', $currentDate);
      $array[] = array( $Store,
       $value->Value2);
      }

      $result = array_merge($array);
    }

This gives the output:这给出了输出:

 0 => array:2 [▼
    0 => "2019-11-24"
    1 => "4"
  ]
  1 => array:2 [▼
    0 => "2019-11-24"
    1 => "10"
  ]

However, I would like to shape the array in such a way that I get the sum of the 2nd field per day without duplicates.但是,我想以这样的方式塑造数组,即每天获得第二个字段的总和而没有重复。 like:喜欢:

 0 => array:2 [▼
    0 => "2019-11-24"
    1 => "14"
  ]

However, I cannot get any further.但是,我不能再进一步了。

You can make the date a key, then sum index 1 if date is same.您可以将日期作为键,如果日期相同,则将索引1相加。

$result = [];
foreach($array as $v){
    if(isset($result[$v[0]])){
        $result[$v[0]][1] += $v[1];
    }else{
        $result[$v[0]] = $v;
    }
}
$result = array_values($result);

I don't follow your previous logic, so perhaps you can sum as you are iterating through your database results, but given your output:我不遵循您以前的逻辑,因此也许您可以在迭代数据库结果时进行总结,但考虑到您的输出:

<?php

$dates =
[
    [
        '2009-11-24',
        2
    ],
    [
        '2009-11-24',
        5
    ]
];

foreach($dates as $date) {
    $result[$date[0]][] = $date[1];
}
$result = array_map('array_sum', $result);
$result = array_map(null, array_keys($result), $result);

var_export($result);

Output:输出:

array (
  0 => 
  array (
    0 => '2009-11-24',
    1 => 7,
  ),
)

The first foreach produces this as the result:第一个 foreach 结果如下:

array(1) {
    ["2009-11-24"]=>
    array(2) {
      [0]=>
      int(2)
      [1]=>
      int(5)
    }
  }

Then the array_map and array_sum results in this:然后 array_map 和 array_sum 结果如下:

  array(1) {
    ["2009-11-24"]=>
    int(7)
  }

The last array_map rejigs into the original format, an array of arrays with the date and the summed values for the first and second index of each.最后一个 array_map 重新调整为原始格式,一个数组数组,其中包含日期以及每个数组的第一个和第二个索引的总和值。

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

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