使用PHP合并数组中的数据

时间:2018-07-11 12:44:43

标签: php arrays

我有这个类型的数组

Array
(
    [0] => Array
        (
            [id] => 90
            [name] => Paul
            [company] => Google
            [date] => 2018-01-06
            [total] => 100.00
        )
    [1] => Array
        (
            [id] => 90
            [name] => Paul
            [company] => Google
            [date] => 2018-07-06
            [total] => 100.00
        )
    [2] => Array
        (
            [id] => 89
            [name] => Ethan
            [company] => Yahoo
            [date] => 2018-07-10
            [total] => 1140.00
        )
)

我需要通过合并idname(如果相同)来从前一个数组创建一个新数组。

所需的输出应为:

[[
    [id] => 90
    [name] => Paul
    [company] => Google,
    [data] => [
        [date] => 2018-01-06,
        [total] => 100.00
    ],
    [
        [date] => 2018-07-06,
        [total] => 100.00
    ],
], [
    [id] => 89
    [name] => Ethan
    [company] => Yahoo
    [data] => [
        [date] => 2018-07-10,
        [total] => 1140.00
    ]
]]

我以前尝试过的东西:

$output = array();
foreach($input as $data){
    $output[$data['id']][] = $data;
    $output[$data['name']][] = $data;
    $output[$data['company']][] = $data;
}

请问我在这里想念什么?

谢谢。

1 个答案:

答案 0 :(得分:3)

这应该是您想要的东西:

foreach ($arr as $a) {
    if (empty($resp[$a['id']])) {
        $resp[$a['id']] = [
            'id' => $a['id'],
            'name' => $a['name'],
            'company' => $a['company'],
            'data' => []
        ];
    }
    $resp[$a['id']]['data'][] = [
        'date' => $a['date'],
        'total' => $a['total']
    ];
}

这是假设您只关心将日期和总计分组为重复的公司和名称。