按指定的键值对对数组进行分组

时间:2017-08-05 17:55:41

标签: php arrays

Heys家伙我有以下数组:

Array
(
    [0] => Array
        (
            [date] => 2017-03-31
            [1] => 7.9950
        )

    [1] => Array
        (
            [date] => 2017-06-30
            [1] => 8.3425
        )


    [2] => Array
        (
            [date] => 2017-03-31
            [2] => 6.8250
        )

    [3] => Array
        (
            [date] => 2017-06-30
            [2] => 10.7725
        )


    [4] => Array
        (
            [date] => 2017-03-31
            [3] => 6.4950
        )

    [5] => Array
        (
            [date] => 2017-06-30
            [3] => 7.3425
        )

)

我需要将共享相同日期的所有值合并到一个数组中,如果可能,保留原始键。他们是id,我将json_encode建立一个图表。

Array
(
    [0] => Array
        (
            [date] => 2017-03-31
            [1] => 7.9950
            [2] => 6.8250
            [3] => 6.4950
        )

    [1] => Array
        (
            [date] => 2017-06-30
            [1] => 8.3425
            [2] => 10.7725
            [3] => 7.3425
        )
)

有没有办法实现这个目标?我已经找了类似的问题,在php手册中查找了array_merge等相似的函数,但无法达到预期的效果。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

这样的事情怎么样:

$output = array();
foreach($input as $record){
  foreach($record as $key => $value){
    $output[$record['date']][$key] = $value;
  }
}
//make it a regular array
$output = array_values($output);

任何重复数据只会出现一次。