gpt4 book ai didi

php - 查询数据库后使用 php 进行转置

转载 作者:行者123 更新时间:2023-11-29 03:41:37 25 4
gpt4 key购买 nike

我正在使用 PHP 查询 MYSQL 数据库,并尝试将数据输出到 excel 文件。

我使用过 phpexcel、csv 等。我已经成功地将数据输出到 excel 文件,但我似乎无法在 excel 中转置它(转置 - 将所有列翻转为行,并且行成列)

我找不到任何教程来帮助我。

我的问题是,有没有办法使用 php 将这些行和列从 MYSQL 转置并导入到 excel 文件中?

谢谢!

代码:

exportMysqlToCsv($tablename,$tokenmain, $id);
function exportMysqlToCsv($tablename,$tokenmain, $id, $filename = 'Results.csv'){
$sql_query = "select * from $tablename where token=1";

// Gets the data from the database
$result = mysql_query($sql_query);

$f = fopen('php://temp', 'wt');
$first = true;

//trying to transpose the data
function transpose($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);}

//inserting it into the excel file
while ($row = mysql_fetch_assoc($result)) {

if ($first) {

fputcsv($f, array_keys($row));

$first = false;

}

fputcsv($f, $row);
}
} //end while

数据库示例:

=======================================
| Male/female | Favorite artist |
=====+========+===============+=======|
| F | Britney Spears |
|-------------------------------------|

我希望它看起来像什么:

=====================================
|Question | Answer |
=====+========+===============+=====|
| Male/female | F |
|----+--------+---------------+-----|
| Favorite artist | Britney Spears |
|----+--------+---------------+-----|

重要提示:在 php 中没有更改数据库/硬编码数组。我希望一切都是动态的,数据库将保持原样

最佳答案

为了回答我的问题,这是我使用 PHPExcel 的代码:

$col=1; // 1-based index
while($row_data = mysql_fetch_assoc($result)) {

$row= 1;

foreach ($row_data as $key=>$value) {

$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$row++;
}
$col++;

}

$row=1;
while($row_data = mysql_fetch_assoc($result2)) {
$col=0;

foreach($row_data as $value) {

$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$row++;

$col++;}
}

调换列(col)和行(row),使数据库中的列变成excel文件中的行,行变成列。

关于php - 查询数据库后使用 php 进行转置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13146949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com