如何使用php在多维数组中按键对项目进行分组

时间:2016-06-05 23:27:23

标签: php arrays group-by

我有一个包含我想要分组的数据的数组,例如:

[

{
    "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
}

]

我想做的是按日期将它们组合在一起并计算出发射值(按日期求和);

因此重复的数组如:{     “日期”:“04-06-2016”,     “发射”:3450 }

应该只存在一次,并且emmission应该是sum,我已经尝试了几乎所有从array_unique到array_search但仍然没有运气。

由于

我现在拥有什么

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');

随着我得到唯一的日期,但最后一个元素的发射是零

1 个答案:

答案 0 :(得分:1)

一个错字:" emmission"拼写"发射"

可能的解决方案是使用两个循环。首先将按日期分组的所有排放总和作为关键,然后再重新构建对象。

<?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}]