简体   繁体   English

使用PHP合并数组中的数据

[英]Merging datas from an array with PHP

I have this type array 我有这种类型的数组

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

I need to create a new array from the previous one by merging id and name if they are the same. 我需要通过合并idname来创建一个新的数组,如果它们是相同的。

The desired output should be: 期望的输出应该是:

[[
    [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
    ]
]]

What I have tried before: 我以前尝试过的:

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

What I'm missing here please ? 我在这里想念的是什么?

Thanks. 谢谢。

This should be something like what you're looking for: 这应该是你想要的东西:

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']
    ];
}

This is assuming that you only care about grouping the date and total into a repeated company and name. 这假设您只关心将日期和总数分组为重复的公司和名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM