-2

我有一个多维数组。我需要用相同的“驱动程序”和“日期”键来总结距离值

Input : 

$firstArr = array(
0 =>array('driver'=>'xxxx',
                    'distance' => 100,
                    'vehicle' => 1,
                    'date' => '2019-10'),

1=>array('driver'=>'xxxx',
                    'distance' => 200,
                    'vehicle' => 2,
                    'date' => '2019-10'),
2=>array('driver'=>'yyyy',
                    'distance' => 100,
                    'vehicle' => 3,
                    'date' => '2019-10'));

预期输出:

$finalArr = array(
0 =>array('driver'=>'xxxx',
                    'distance' => 300,
                    'vehicle' => '1,2',
                    'date' => '2019-10'),

1=>array('driver'=>'yyyy',
                    'distance' => 100,
                    'vehicle' => 3,
                    'date' => '2019-10'));

我试过下面的代码。但输出是一个按日期排列的数组。

$subArr = array();
foreach($firstArr as $key => $val){
$subArr[$val['driver']][$val['date']]['distance'] += $val['distance'];
$subArr[$val['driver']][$val['date']]['vehicle'] .= $val['vehicle'].',';
$subArr[$val['driver']][$val['date']]['date'] = $val['date'];
$subArr[$val['driver']][$val['date']]['driver'] = $val['driver'];

}
$result = array_values($subArr); 
4

2 回答 2

2

可以使用dirveranddate作为键,Demo

$result = [];
foreach($array as $v){
    $key = $v["driver"] . "_" . $v["date"];
    if(isset($result[$key])){
        $result[$key]["distance"] += $v["distance"];
    }else{
        $result[$key] = $v;
    }
}
$result = array_values($result);
于 2019-11-25T08:05:23.833 回答
0

您还可以使用array_reduce按驱动程序和日期汇总距离和车辆。在array_combine的帮助下,我们可以为每个驱动程序日期组合设置初始数组(如果不存在),然后对所需字段进行处理。

$keys = array_keys($input[0]);
$result = array_reduce($input, function ($sum, $row) use ($keys) {
    $key = $row['driver'] . $row['date'];
    $sum[$key] = $sum[$key] ?? array_combine($keys, [$row['driver'], null, null, $row['date']]);
    $sum[$key]['distance'] += $row['distance'];
    $sum[$key]['vehicle'] .= (($sum[$key]['vehicle']) ? ',': '' ) . $row['vehicle'];
    return $sum;
}, []);

结果是:

Array
(
    [xxxx2019-10] => Array
        (
            [driver] => xxxx
            [distance] => 300
            [vehicle] => 1,2
            [date] => 2019-10
        )

    [yyyy2019-10] => Array
        (
            [driver] => yyyy
            [distance] => 100
            [vehicle] => 3
            [date] => 2019-10
        )

)
于 2019-11-25T09:30:20.240 回答