我有一个数组,其中包含要分组的数据,示例如下:

[

{
    "date": "04-06-2016",
    "emmission": 3450
},
{
    "date": "04-06-2016",
    "emmission": 91
},
{
    "date": "09-02-2016",
    "emmission": 10
},
{
    "date": "04-06-2016",
    "emmission": 7
},
{
    "date": "19-04-2016",
    "emmission": 28
},
{
    "date": "08-05-2015",
    "emmission": 7
},
{
    "date": "04-06-2016",
    "emmission": 15
},
{
    "date": "04-06-2016",
    "emmission": 109
}

]

我要做的是按日期将它们组合在一起并计算emmission值(按日期求和);
因此重复的数组如下:{
“date”:“2016年6月4日”,
“发射”:3450
}
应该只存在一次,放出应该是总和,我尝试了几乎所有从ARARYAY独特到ARARYY搜索,但仍然没有运气。
谢谢
我现在拥有的
public function unique_multidim_array($array, $key) {
    $temp_array = array();
    $i = 0;
    $key_array = array();

    foreach($array as $val) {
        if (!in_array($val[$key], $key_array)) {
            $key_array[$i] = $val[$key];
            $temp_array[$i] = $val;

             // $temp_array[$i]['emmission'] += $array[$i]['emmission'];
        }

        $i++;
    }
    return $temp_array;
}

$this->unique_multidim_array($history, 'date');

这样我得到了唯一的日期,但是最后一个元素的emmission为零

最佳答案

一个错别字:“emmission”拼写为“emission”
一个可能的解决方案是使用两个循环。首先将按日期分组的所有排放量相加作为键,然后重建对象。

<?php
$json = '[

{
    "date": "04-06-2016",
    "emission": 3450
},
{
    "date": "04-06-2016",
    "emission": 91
},
{
    "date": "09-02-2016",
    "emission": 10
},
{
    "date": "04-06-2016",
    "emission": 7
},
{
    "date": "19-04-2016",
    "emission": 28
},
{
    "date": "08-05-2015",
    "emission": 7
},
{
    "date": "04-06-2016",
    "emission": 15
},
{
    "date": "04-06-2016",
    "emission": 109
}

]';

$arr_obj = json_decode($json);

// for each record, if date emission is set, then sum, else set emission
foreach ($arr_obj as $record)
  $dates[$record->date] = isset($dates[$record->date]) ? $dates[$record->date] + $record->emission : $record->emission;

// create array of objects
foreach ($dates as $key => $val)
  $obj_arr []= (object) array("date"=>$key,"emission"=>$val);

$json = json_encode($obj_arr);

echo $json;

输出结果:
[{"date":"04-06-2016","emission":3672},{"date":"09-02-2016","emission":10},{"date":"19-04-2016","emission":28},{"date":"08-05-2015","emission":7}]

关于php - 如何使用php在多维数组中按键对项目进行分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37647779/

10-16 21:41