php中文网

二维数组中如何按日期键名合并数据并汇总数据值?

php中文网

二维数组中如何按键名合并数据?

需要将给定的二维数组进行合并,满足以下条件:

  • 默认以 6 个为单位进行合并,若小于 6 个则正常展示日期
  • 大于 6 个需要合并,例如将 [22-02-05, 22-02-06, 22-02-07, 22-02-08, 22-02-09, 22-02-10] 合并为 22-02-05/22-02-10

解决方案:

$arr = [
    'categories' => [
        '22-01-30',
        '22-01-31',
        '22-02-01',
        '22-02-02',
        '22-02-03',
        '22-02-04',
        '22-02-05',
        '22-02-06',
        '22-02-07',
        '22-02-08',
        '22-02-09',
        '22-02-10',
        '22-02-11',
        '22-02-12',
        '22-02-13',
        '22-02-14',
        '22-02-15',
        '22-02-16',
        '22-02-17',
        '22-02-18',
        '22-02-19',
        '22-02-20',
        '22-02-21',
        '22-02-22',
        '22-02-23',
        '22-02-24',
        '22-02-25',
        '22-02-26',
        '22-02-27',
        '22-02-28',
    ],
    'data'       => [
        '0',
        '0',
        '0',
        '0',
        '0',
        '0',
        '0',
        '0',
        '0',
        '0',
        '5638.04',
        '0.00',
        '0.00',
        '0.00',
        '0.00',
        '0.00',
        '0.00',
        '0.00',
        '0.00',
        '0.00',
        '0.00',
        '0.00',
        '0.00',
        '0.00',
        '25915.99',
        '1606.44',
        '1676.90',
        '0.00',
        '0.00',
        '1203.08',
    ],
];

$chunk = 6;

$result = array_reduce(array_chunk($arr['categories'], $chunk), function ($result, $current) use ($chunk, $arr) {
    $start = current($current);
    $end = end($current);
    $result['categories'][] = $start . '/' . $end;

    $count = count($result['categories'] ?? []);
    $result['data'][] = array_sum(array_slice($arr['data'] ?? [], $count * $chunk, $chunk));

    return $result;
}, ['categories' => [], 'data' => []]);

var_dump($result, (array_sum($arr['data']) === array_sum($result['data'])));

以上就是二维数组中如何按日期键名合并数据并汇总数据值?的详细内容,更多请关注php中文网其它相关文章!