更新 #1 我有一个 php 文件,其中包含多个查询,这些查询创建多个 csv 文件。 我想合并查询。
我的mysql 表
有5列:ID、货币、汇率、日期、临时时间
创建表table
并插入一些记录
CREATE TABLE IF NOT EXISTS `table` ( `id` INT NOT NULL AUTO_INCREMENT , `currency` VARCHAR(254) NOT NULL , `rate` FLOAT NOT NULL , `date` VARCHAR(254) NOT NULL , `temptime` DATE NOT NULL , PRIMARY KEY (`id`), UNIQUE `UNIQUE` (`currency`, `temptime`)) ENGINE = MyISAM;
INSERT INTO `table`
(currency, rate, date, temptime)
VALUES
('USD', '1.232', '1521212400', '2018-03-16'),
('USD', '1.258', '1521126000', '2018-03-15'),
('JPY', '133.82', '1521212400', '2018-03-16'),
('JPY', '131.88', '1521126000', '2018-03-15'),
('EUR', '1.99', '1521212400', '2018-03-16'),
('EUR', '1.85', '1521126000', '2018-03-15'),
('BRL', '1.6654', '1521212400', '2018-03-16'),
('BRL', '1.5498', '1521126000', '2018-03-15'),
('ZAR', '1.99654', '1521212400', '2018-03-16'),
('ZAR', '2.0198', '1521126000', '2018-03-15'),
('RUB', '19.9654', '1521212400', '2018-03-16'),
('RUB', '20.0198', '1521126000', '2018-03-15');
这些是我想要针对“货币”美元和欧元列合并的 2 个查询:
$result = mysql_query("SELECT temptime, rate FROM `table` WHERE currency='USD' ORDER BY date asc");
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('csv/USD.csv', 'w');
if ($fp && $result)
{
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
}
$result = mysql_query("SELECT temptime, rate FROM `table` WHERE currency='EUR' ORDER BY date asc");
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('csv/EUR.csv', 'w');
if ($fp && $result)
{
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
}
谢谢
最佳答案
您可以使用每行中的货币字段来决定要写入哪个文件,我使用了文件句柄数组,因此您只需使用货币作为文件的索引,而不需要围绕哪个文件设置任何条件处理...
// Create an array of files, each associated with currency
$fp = array( 'EUR' => fopen('csv/EUR.csv', 'w'),
'USD' => fopen('csv/USD.csv', 'w'));
$result = mysql_query("SELECT currency, temptime, rate FROM `table` ORDER BY date asc");
if (!$result) die("Couldn't fetch records");
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
// Write out headers to each file.
foreach ( $fp as $output ) {
fputcsv($output, $headers);
}
while ($row = mysql_fetch_row($result)) {
// Use first field to decide which file to write to.
$currency = array_shift($row);
fputcsv($fp[$currency], $row);
}
// Close all of the files.
foreach ( $fp as $output ) {
fclose($output);
}
由于我没有您的数据库,因此无法对此进行测试,但如果您有任何问题,请告诉我。
关于PHP从一个mysql查询创建多个csv文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49335318/