获取数组 - 以CSV结合某些结果

时间:2013-07-01 23:27:43

标签: php mysql sql csv

我正在从SQL数据库中获取结果并使用以下代码将其输出到CSV ...

while ($row = $results->fetch_assoc()) {
    fputcsv($handle, array(
        'admin',
        'base',
        'Default',
        'simple',
        '2', 
        $row['part_id'],
        $row['part_id'],
        $row['price'],
        $row['list_price'],
        $row['core'],
        $row['weight'],
        $row['height'],
        $row['length'],
        $row['width'],
        $row['popularity'],
        $row['qty'],
        $row['description_line_two'],
        $row['detailed_description'],
        $row['note'],
        $row['YearID'],
        $row['MakeID'],
        $row['ModelID'],
        $row['aspiration'],
        $row['bed_length'],
        $row['bed_type'],
        $row['body_num_doors'],
        $row['body_type'],
        $row['brake_abs'],
        $row['brake_system'],
        $row['cylinder_head_type'],
        $row['drive_type'],
        $row['engine_base'],
        $row['engine_designation'],
        $row['engine_version'],
        $row['engine_vin'],
        $row['fuel_delivery_type'],
        $row['fuel_delivery_subtype'],
        $row['fuel_system_design'],
        $row['fuel_type'],
        $row['mfr_body_code'],
        $row['region'],
        $row['steering_system'],
        $row['steering_type'],
        $row['submodel'],
        $row['transmission_control_type'],
        $row['transmission_num_speeds'],
        $row['transmission_type'],
        $row['valves_per_engine'],
        $row['wheel_base']
    ));
}

在数据中,有几个实例,其中部件ID在几行中相同,而其他字段(如年份,品牌,型号)则不同。我希望做的是整合数据。换句话说,如果part_id在两行或更多行之间是一致的,我想将其他一些字段(例如year,make,model)组合成一行。

换句话说,它现在就像这样......

Part ID    Year    Make    Model
0001       2013    Suzuki  NA
0001       2012    Acura   NA
0001       2011    Hyundai Elantra

我希望它像......

Part ID    Year              Make                      Model
0001       2013,2012,2011    Suzuki, Acura, Hyundai    NA, Elantra

这一切都可能吗?如果是这样,我将如何去做呢?

如果有帮助,我打开QUERY来操作数据库中的数据,如果有帮助的话!

1 个答案:

答案 0 :(得分:1)

或许这样的事情:

CREATE TEMPORARY TABLE tmp_table
SELECT 'admin' as custom1,'base' as custom2,part_id,year... etc
FROM original_table
WHERE 1;

然后你想从那里选择你的东西,并把分组放在:

SELECT part_id, custom1, GROUP_CONCAT(year) as year
FROM tmp_table
WHERE 1
GROUP BY part_id

不确定结构或分组,但谷歌搜索和参考搜索应该填补空白。这个概念就在那里,你要找的是MySQL的GROUP_CONCAT功能(http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html