我有一个来自我的数据库的名字列表。
我正在尝试将 PDO::fetchAll() 函数的结果转换为类似字符串的结果:
“名称 1”、“名称 2”、“名称 3”等。
我不知道你是否明白我的意思。
谢谢大家的帮助!
the very fetchAll()
manual page contains the code that lets you get 1-dimensional array which can be easily imploded
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
you could also use Mysql's group_concat()
function to get the string already from SQL.
But it is critical to know the destination of the data.
发现这个,天知道在哪里,很久以前就完成了这个任务。我希望你觉得这对你有帮助:
/**
* Formats a line (passed as a fields array) as CSV and returns the CSV as a string.
* Adapted from http://us3.php.net/manual/en/function.fputcsv.php#87120
*/
function arrayToCsv( array &$fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
$output = array();
foreach ( $fields as $field ) {
if ($field === null && $nullToMysqlNull) {
$output[] = 'NULL';
continue;
}
// Enclose fields containing $delimiter, $enclosure or whitespace
if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
$output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
}
else {
$output[] = $field;
}
}
return implode( $delimiter, $output );
}